I have the following code. The mysqli_insert_id() (in this case "$last_row"), which is supposed to return the last row of the table, is always returning 0. Why is it so?
<?php
include 'connect-db.php';
$last_row = mysqli_insert_id($connection);
if ($content != '') {
$sql = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($connection));
}
echo $last_row;
mysqli_close($connection);
}
mysqli_insert_id does not return the ID of the last row of the table. From the docs, it:
...returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.
(My emphasis)
That is, if you were to run it immediately after an insert that auto-generated an ID, on the same connection you did the insert with, it would return the ID generated for that insert.
This is illustrated by the example in the docs linked above:
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
To get the result, you should place the
$last_row = mysqli_insert_id($connection);
after your INSERT query
Maybe you tried INSERT IGNORE INTO and you have a UNIQUE value that was already inserted. In that case, this id is zero.
Also, you'll get "zero" if MySQL runs out of connections.
As you probably know PHP “mysql” extension supported persistent
connections but they were disabled in new “mysqli” extension
--Peter Zaitsev
Another gotcha with this function -- if you're doing:
INSERT INTO table (col1, col2) VALUES (1, 2) ON DUPLICATE KEY UPDATE col2=3
and insert doesn't happen because of a duplicate key and for the UPDATE, like in my case, if col2 was already set to 3, then mysqli_insert_id will also return 0.
Related
I'm using mysqli in a PHP class.
I have this query to be executed:
INSERT INTO notifications (userid, content, uniq, link) VALUES (48, "[2014-07-30] Nomid has edited the post \"Somepost\"", "934512e1e9314d9c602a02a26114a625", "http://website/somepost")
It fails, showing the error:
You have an error in your query etc. to use near '"[2014-07-30] Nomid has edited the post \"Somepost\"", "934512e1e9314d9"'
But if I look in the DB, the new row is present.
The parameters are escaped using mysqli_real_escape_string():
$msg = $this->escape($msg);
$uniqid = $this->escape($uniqid);
$sql = "INSERT INTO notifications (userid, content, uniq, link) VALUES ($userid, \"$msg\", \"$uniqid\", \"$link\")";
// die($sql);
$this->query($sql);
I tried to check query execution with $mysqli->affected_rows and !$result of mysqli_query().
The fields types are
INT (11) for userid,
TEXT for content,
TINYTEXT for uniq and
TINYTEXT for link.
All of the TEXT fields have collation "utf8_general_ci".
I didn't create the table.
The strange thing is that if I look in the database, the query was successfully executed...
Why is this happening?
you sql should be like
$userid = $this->escape($userid);
$msg = $this->escape($msg);
$uniqid = $this->escape($uniqid);
$link = $this->escape($link);
$sql = "INSERT INTO notifications (userid, content, uniq, link) VALUES ('$userid', '$msg', '$uniqid', '$link')";
Here's my code:
$con=mysqli_connect("localhost","name","pass","bird") ;
$result = mysqli_query($con,"SELECT * FROM bird");
mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values (0,'d','cwer','73')");
the first time, I could see the the values were added but when I reloaded, it didn't do any more, is it supposed to be like this ?
So if I want it to run every time I reload, how can I do that?
You probably have a unique constraint against your id column (or another column in that query) and when you try to add a second row using the same ID it is rejected by MySQL.
You should be doing error checking in your code. You should be checking to see how many rows were affected by your insert (using mysqli_affected_rows()) and, if the number is zero, getting the error message from MySQL (using mysqli_error()).
$result = mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values (0,'d','cwer','73')");
if (mysqli_affected_rows() === 0) {
echo mysqli_error($con);
}
#DaveChen's comment above is a good solution to your (potential) problem. If it isn't already, make your id column auto increment and then leave it out of your query.
mysqli_query($con,"INSERT INTO 'bird' (`name`, `latin`, `number`) values ('d','cwer','73')");
If your id column is aut_increment and unique: change your code to:
$con=mysqli_connect("localhost","name","pass","bird") ;
$result = mysqli_query($con,"SELECT * FROM bird");
mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values ('','d','cwer','73')");
I have the following code. The mysqli_insert_id() (in this case "$last_row"), which is supposed to return the last row of the table, is always returning 0. Why is it so?
<?php
include 'connect-db.php';
$last_row = mysqli_insert_id($connection);
if ($content != '') {
$sql = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($connection));
}
echo $last_row;
mysqli_close($connection);
}
mysqli_insert_id does not return the ID of the last row of the table. From the docs, it:
...returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.
(My emphasis)
That is, if you were to run it immediately after an insert that auto-generated an ID, on the same connection you did the insert with, it would return the ID generated for that insert.
This is illustrated by the example in the docs linked above:
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
To get the result, you should place the
$last_row = mysqli_insert_id($connection);
after your INSERT query
Maybe you tried INSERT IGNORE INTO and you have a UNIQUE value that was already inserted. In that case, this id is zero.
Also, you'll get "zero" if MySQL runs out of connections.
As you probably know PHP “mysql” extension supported persistent
connections but they were disabled in new “mysqli” extension
--Peter Zaitsev
Another gotcha with this function -- if you're doing:
INSERT INTO table (col1, col2) VALUES (1, 2) ON DUPLICATE KEY UPDATE col2=3
and insert doesn't happen because of a duplicate key and for the UPDATE, like in my case, if col2 was already set to 3, then mysqli_insert_id will also return 0.
I have the following lines of PHP code in my file along with some other code:
$command = "INSERT INTO inventory_items (Index, Name, Price) VALUES (NULL, 'Diamond', '3.99')";
$insertion = mysql_query($command) or die(mysql_error());
if ($insertion == FALSE)
{
echo "Error: Insert failed.";
}
else
{
echo "Insert successful.";
}
It keeps returning this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Index, Name, Price) VALUES (NULL, 'Diamond', '3.99')' at line 1
myAdmin says I am using MySQL client version 5.0.91. What am I doing wrong? I just can't figure it out! I tried searching a lot...
Index is a reserved word in MySQL and as such, you need to either change the name of the column, or escape it with backticks. Try this $command:
$command = "INSERT INTO inventory_items (`Index`, Name, Price) VALUES (NULL, 'Diamond', '3.99')";
Read more about reserved words here: http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html
Try this:
$command = "INSERT INTO inventory_items (`Index`, Name, Price) VALUES (NULL, 'Diamond', '3.99');";
MySQL reserved words and how to treat them.
Can you verify that the columns in your inventory_items table are:
Index
Name
Price
And that you have the Index field set to AUTO_INCREMENT.
The best thing is probably to remove that field from your insert statement.
Try
$command = "INSERT INTO inventory_items (Name, Price) VALUES ('Diamond', '3.99')";
Since you're not inserting an Index anyway.
Hope that helps!
i have a recipe table and ingredient table the primary key of both tables are auto increament and primary key of recipe is foreign key in ingredient. i post data from html to php.Note that my ingredient textboxes are generated dynamically and successfully post the data to php script. posted data is correct when i insert this data to table my query working fine but data is not added to mysql table. my code and output is
$sql = "insert into recipe (rec_id, Name, Overview,category, Time, Image) values ('', '$name','$overview','$category','$time','$TARGET_PATH')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
$rec_id = mysql_insert_id();
and for ingredient
$ingredient = $_POST['ingredient'];
$amount = $_POST['amount'];
$integer = 0;
while (count($ingredient)>$integer) {
if (($ingredient[$integer] <> "") && ($amount[$integer] <> "")){
$sql = "INSERT INTO `cafe`.`ingredients` (`ingredient_id`, `ingredient_name`, `ammount`, `rec_id`,)
VALUES ('', '".$ingredient[$integer]."', '".$amount[$integer]."', '$rec_id')";
mysql_query($sql);
echo $sql."";
}
else{
echo "ingredient number ".($integer+1)." is missing values and cannot be inserted.";
}
$integer = ($integer + 1);
}
when i echo the queries the out put is nsert into recipe (rec_id, Name, Overview,category, Time, Image) values ('', 'demo recipe','no overview','meal','10/12/10 : 13:02:33','http://www.localhost/cafe/pics/demo.gif')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient one', '3gm', '29')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient two', '3gm', '29')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient three', '3gm', '29')
but when i see the mysql table or retriew data from ingredient there is no data in ingredient.
You have an extra , after rec_id.
Remove it, so it looks like
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id) VALUES ('', 'ingredient one', '3gm', '29')
And you will be OK
There seems to be a syntax error in your code:
if (($ingredient[$integer] "") && ($amount[$integer] ""))
^^ ^^
Looks like you are missing a comparison operator.
You might want to verify if you are using a BEGIN call and not committing after INSERT. You can refer to http://www.devarticles.com/c/a/MySQL/Using-Transactions-with-MySQL-4.0-and-PHP/
in that scenario.
When insert doesnt throw exceptions and doesnt insert data there are I think a couple of options
1) you use transaction somewhere and rollback it
2) your select query is bad and data is there, but you just dont select it
remove cafe from the query
$sql = "INSERT INTO ingredients (`ingredient_id`, `ingredient_name`, `ammount`, `rec_id`,)
VALUES ('', '".$ingredient[$integer]."', '".$amount[$integer]."', '$rec_id')";