I have a small php page like below that I would like to return the "auto-incremented_id" from this insert.
Only requirement is that I can read the number from an android application. I'm sure I could look it up but is there a code SQL
code I can check on success that will return it?
Here's the php:
<?php
//Make connection
$con = mysqli_connect('xxxxx', 'xxxxxxx', 'xxxxx');
//check connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//change db to andriodnfp db
mysqli_select_db($con, 'andriodnfp');
$table = 'USER';
$fbid = htmlspecialchars($_GET["fbid"]);
$social = htmlspecialchars($_GET["social"]);
$name = htmlspecialchars($_GET["name"]);
$name = !empty($name) ? "'$name'" : "NULL";
$fname = htmlspecialchars($_GET["fname"]);
$fname = !empty($fname) ? "'$fname'" : "NULL";
$username = htmlspecialchars($_GET["username"]);
$username = !empty($username) ? "'$username'" : "NULL";
$email = htmlspecialchars($_GET["email"]);
$email = !empty($email) ? "'$email'" : "NULL";
$picture = htmlspecialchars($_GET["picture"]);
$picture = !empty($picture) ? "'$picture'" : "NULL";
$other = htmlspecialchars($_GET["other"]);
$other = !empty($other) ? "'$other'" : "NULL";
if (!$fbid == '') {
if (!mysqli_query($con, 'INSERT INTO ' . $table . ' ( facebookID, social_outlet, Name, first_name, username, email, picture, significant_other) VALUES ("' . $fbid . '","' . $social . '","' . $name . '","' . $fname . '","' . $username . '","' . $email . '","' . $picture . '","' . $other . '")')) {
printf("Errormessage: %s\n", mysqli_error($con));
};
}
mysqli_close($con);
//$posts = array($json);
$posts = array(
1
);
header('Content-type: application/json');
echo json_encode(array(
'posts' => $posts
));
?>
Try this: mysqli_insert_id
if (mysqli_query($con, 'INSERT INTO '.$table.' ( facebookID, social_outlet, Name, first_name, username, email, picture, significant_other) VALUES ("'.$fbid.'","'.$social.'","'.$name.'","'.$fname.'","'.$username.'","'.$email.'","'.$picture.'","'.$other.'")') === false) {
printf("Errormessage: %s\n", mysqli_error($con));
die();
}
$id = mysqli_insert_id($con);
You should also probably die
after an error.
Also, you should compare the query with datatype as well ===
, this ensures that it truly failed, not returned a value which evaluates to false. -- but it's not likely it returned something for an insert right?
Suppose you have a table in the database that looks like this:
id, username, user_level
1, dave, 0
2, jcaruso, 1
Suppose user_level
was an integer, (0 = user, 1 = administrator).
Doing a select such as SELECT user_level FROM table WHERE id=1
would return 0
and if you compare that with ==
, it would be true. 0==false
.