Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get success/failure response from mysqli_query

Tags:

php

mysql

I'm gathering info from a user and then adding them to a table.

$insert = "INSERT INTO jos_activeagents (RINGPHONE, AGENTUID, FNAME, LNAME) VALUES ('(618) 717-2054','".$result['AGTBRDIDMM']."','".$result['AGTFNAME']."','".$result['AGTLNAME']."')";

$set = mysqli_query($link,$insert);

AGENTUID is a unique key. If a user tries to submit with a duplicate unique key, I get an error (of course).

Now, how would I go about knowing if and when an error occurred and then putting a response back to the page? I know of mysqli_get_warnings(), but the PHP manual doesn't show any examples.

I have also tried looking for the AGENTUID in the table first:

$check = "SELECT * FROM jos_activeagents WHERE AGENTUID = '".$agt."'";

$runcheck = mysqli_query($link,$check);

$rescheck = mysqli_fetch_assoc($runcheck);

if($rescheck != null){

    echo 'This Agent ID is already enrolled.'

}

But this seems sloppy. Is there a better way do this?

like image 299
Plummer Avatar asked Apr 26 '13 14:04

Plummer


People also ask

What is the result of mysqli_query?

For successful queries which produce a result set, such as SELECT, SHOW, DESCRIBE or EXPLAIN , mysqli_query() will return a mysqli_result object. For other successful queries, mysqli_query() will return true .

What does mysqli_query return if empty?

For other successful queries mysqli_query() will return TRUE. The result can still be empty even if it was succesful. If you use pdo, as suggested above. You get an array back (empty array if result is empty) so you can do sizeof($array) or count($array) to check if you have 0 results or not.

What does the Mysqli_error () function do?

The error / mysqli_error() function returns the last error description for the most recent function call, if any.

How many parameters does the mysqli_query () function accept?

PHP uses mysqli query() or mysql_query() function to create or delete a MySQL database. This function takes two parameters and returns TRUE on success or FALSE on failure.


1 Answers

You can use mysqli_error() to see if an error occurred

if (mysqli_error($runcheck ))
{
   // an error eoccurred
}

In your particular example you're better of checking if the row exists before doing the insert. Your example is close but would better using mysqli_num_rows():

$check = "SELECT * FROM jos_activeagents WHERE AGENTUID = '".$agt."'";
$runcheck = mysqli_query($link,$check);
if (mysqli_num_rows($runcheck) > 0)
{
    // username in use
}
like image 56
John Conde Avatar answered Oct 02 '22 15:10

John Conde