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?
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 .
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.
The error / mysqli_error() function returns the last error description for the most recent function call, if any.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With