Mysqli insert id returning null - php

$S = "INSERT INTO ". TBD ." (NODE, AV, BV) VALUES ('15', '$name', '$email')";
$Q = $CONN->query($S);
$M = $Q->insert_id;
$M returns NULL not 0
The above script runs the query fine, but will not return the unique ID generated.
The table, definitely has a auto increment and is a primary key.
I have used the script elsewhere and works fine.
So I have no idea why its returning NULL now.

I think you are calling insert_id wrong. Try this:
$S = "INSERT INTO ". TBD ." (NODE, AV, BV) VALUES ('15', '$name', '$email')";
$Q = $CONN->query($S);
$M = $CONN->insert_id;

You need to extract the insert_id from the connection object and not the result set.
Your $Q variable is a mysqli result object so you'll want to extract the inserted id like this:
$CONN->insert_id;

Related

Can't get mysql_insert_id() method to grab value I need

I'm trying to grab SID from the insert into the first table (stories) so I can insert that SID into the writing table in my second insert.
I think the way to do this is with mysql_insert_id(); after the first query, but the primary key that auto-increments is called SID. If mysql_insert_id() could grab that value I'd be all set.
What I am finding from a var_dump is that the $SID = mysql_insert_id(); is just returning the value "0" and I'm not sure why.
There is a column called ID in stores, but if it was grabbing that, the value would be "1". Either way, I wish this method could be written as mysql_insert_SID();
Any idea what I am doing wrong or how I can fix this? And yes, I know this is a deprecated approach, but first I want to figure out how before I worry about converting to PDO.
// Get values from form
$category = $_POST['category'];
$genre = $_POST['genre'];
$story_name = $_POST['story_name'];
$text = $_POST['text'];
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query);
$SID = mysql_insert_id();
$SID2 = "select stories.SID from stories where stories.SID=$SID";
$query2 = "INSERT INTO writing (ID, SID, text, position, approved)
VALUES('$user_ID', '$SID2', '$text', '1','N')";
$result = mysql_query($query2);
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
(http://php.net/manual/en/function.mysql-insert-id.php)
But you aren't executing any query (via mysql_query()). You're just assigning your query to a variable. Try following:
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
mysql_query($query);
$SID = mysql_insert_id();
I think you've forgotten to execute the query most probably?
Try
$SID = mysql_insert_id();
after executing the query
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query); // executing
$SID = mysql_insert_id(); // order of queries is important
If you cannot get the value through mysql_insert_id() then try SELECT LAST_INSERT_ID(). Of course there will be a value if you have executed an insert query with AUTOINCREMENT (which you haven't done yet)

Query not working - INSERT INTO

So i recently starting learning PHP, and now im trying to get code into my database.
The data is input from the user through a form.
here is my code:
if(isset($_POST['submit'])) {
$blogtitle = $_POST['blogTitle'];
$blogcategory = $_POST['blogCategory'];
$blogcontent = $_POST['blogContent'];
// aanmaak date van de blog
$blogdate = date("d/m.Y");
// Checkt of alle velden zijn ingevuld
if (!empty($blogtitle) && !empty($blogcategory) && !empty($blogcontent)) {
//echo "je zit nu bij de query";
$addBlogQuery = mysql_query("INSERT INTO blog (blog_ID, blog_title, blog_category, blog_content, blog_date)
VALUES (NULL, $blogtitle, $blogcategory, $blogcontent, blogdate )");
if ($addBlogQuery) {
echo "blog added successfully";
}
else {
echo "something went wrong";
}
}
else {
$this->notFilledErrorAction();
}
}
For some reason it's not adding any data my database. My connection to my database is working properly, and i dont see a mistake in my query.
Does someone see an error in this code? or could help me figure out the problem?
You have a syntax error in your INSERT statement:
$addBlogQuery = mysql_query("INSERT INTO blog (blog_ID, blog_title, blog_category, blog_content, blog_date)
VALUES (NULL, $blogtitle, $blogcategory, $blogcontent, blogdate )");
You are missing a $ here------------------------^
You also need to wrap your variables in ' single quotes:
$addBlogQuery = mysql_query("INSERT INTO blog (blog_ID, blog_title, blog_category, blog_content, blog_date)
VALUES (NULL, '$blogtitle', '$blogcategory', '$blogcontent', '$blogdate' )");
Furthermore, the mysql_* API is now deprecated. Please read the big red box here. You should start using MySQLi or PDO now whilst it is still relatively easy to change.
You need to enclose strings ,date and DATETIME values with single quotes (').
And you have not enclosed in your SQL.
Please modify your SQL as:
$addBlogQuery = mysql_query("INSERT INTO blog (blog_ID, blog_title, blog_category, blog_content, blog_date)
VALUES (NULL, '$blogtitle', '$blogcategory', '$blogcontent', 'blogdate' )");
Mysql support only following date format:
YYYY-mm-dd
but your code has different format
$blogdate = date("d/m.Y");
Try the following:
$blogdate = date("Y-m-d");
And you have passed ID null, i think you have selected ID as primary key. primary key can not be null. if your ID field support auto-increment you don't need to pass anything.
$addBlogQuery = mysql_query("INSERT INTO blog (blog_title, blog_category, blog_content, blog_date)
VALUES ($blogtitle, $blogcategory, $blogcontent, blogdate )");
Hopefully it will work.
See the changes below and try again:
$blogdate = date("Y-m-d");
$addBlogQuery = mysql_query("INSERT INTO `blog` (`blog_title`, `blog_category`, `blog_content`, `blog_date`)
VALUES ('$blogtitle', '$blogcategory', '$blogcontent', '$blogdate' )");
Use more secure way , Use PDO - Stop using MYSQL_* it's deprecated
PDO escapes itself, you doesn't need to use mysql_real_escape_string
<?php
$user="root";
$pass="";
$db = new PDO('mysql:host=hostname;dbname=databasename', $user, $pass); //establish new connection
$sql ="INSERT INTO blog (blog_ID, blog_title, blog_category, blog_content, blog_date)
VALUES (NULL, ?, ?, ?, ?)";
try{
$stmt = $db->prepare($sql);
$stmt->execute(array($a, $b, $c, $d));
if($stmt->rowCount()>0){
//done
}
}catch(PDOException $e){
echo $e->getMessage();
?>
Before inserting into database you should sanitize you data to prevent SQL injection and XSS. Use this function:
function sanitize($data){
$data= htmlentities(strip_tags(trim($data)));
return $data;
}
Try following query there is no need to use php date function mysql has native support to date and time functions
INSERT INTO blog
(`title`, `category`, `content`, `date`, `id`)
VALUES
('Title here', 'category here','blog content here', NOW(), 1);
here is SQL test SQL Fiddle
$addBlogQuery = mysql_query("INSERT INTO blog (blog_title, blog_category, blog_content, blog_date) VALUES ($blogtitle, $blogcategory, $blogcontent, blogdate )");
It seems your mistake is insert the value of blog_id by NULL. blog_id column is the primary key. If you insert blog_id by NULL, then the data can't push to your database. Since blog_id is primary key, you don't need to insert blog_id manually. It will automatically inserted.

Why is mysqli_insert_id() always returning 0?

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.

PHP not getting parameters

I acces my page passing some parameters through the URL:
www.mypage.com/page.php?aID=4091cdcd-773d-4ca5-bab2-41e1188870a9&sID=1_MX4yMjI1MTgxMn4xMjcuMC4wLjF-V2VkIERlYyAyNiAwOTo1MDoyNiBQU1QgMjAxMn4wLjg1MjA4MTF-&nam=Gab&tel=7777777777
then in my PHP code I have:
if(isset($_GET['sID'])) {
$sID = $_GET['sID'];
}
if(isset($_GET['aID'])) {
$aID = $_GET['aID'];
}
if(isset($_GET['nam'])) {
$nam = $_GET['nam'];
}
if(isset($_GET['tel'])) {
$tel = $_GET['tel'];
}
I have no problem retrieving $nam and $tel, but $aID and $sID always get an empty string. I have tried using double quotes (isset($_GET["aID"])) , but it has not made any difference.
Are there illegal characters on the string or a limit in size of a variable you can pass through the URL? How can I GET variables $aID and $sID?
$query = "INSERT INTO myTable (ArchiveID, SessionID, Name, Tel) VALUES ('$aiD', '$siD', '$nam', '$tel' )";
echo $query;
Echo $query's output is:
INSERT INTO myTable (ArchiveID, SessionID, Name, Tel) VALUES ('', '', 'Gab', '7777777777' )
Testing your URL, I get the following result:
Array
(
[aID] => 4091cdcd-773d-4ca5-bab2-41e1188870a9
[sID] => 1_MX4yMjI1MTgxMn4xMjcuMC4wLjF-V2VkIERlYyAyNiAwOTo1MDoyNiBQU1QgMjAxMn4wLjg1MjA4MTF-
[nam] => Gab
[tel] => 7777777777
)
Therefore, I'm not sure what you mean by you're getting an empty string. You did have a typo in your code, where $tel references $_GET['aID']. I would advise you verify your code.
I would recommend that you also use $_SERVER['REQUEST_METHOD'] to verify that your script is using GET.
Update
Per your updated query, it seems as though your case is incorrect. The variable name is case-sensitive.
$query = "INSERT INTO ... VALUES ('$aiD', '$siD', '$nam', '$tel' )";
^ ^
Should be:
$query = "INSERT INTO ... VALUES ('$aID', '$sID', '$nam', '$tel' )";
You have to enable error reporting and logging to the highest level when you develop PHP.
You have to check return values of methods you call to see if they did what you thought they did. You have to look for more error information if something failed.
You have to look into prepared statements to prevent SQL injection.
And yes, mysql_* functions are deprecated. Do not use it for new code.
You notice in your sql statement you are not calling the variables you defined:
$query = "INSERT INTO myTable (ArchiveID, SessionID, Name, Tel) VALUES ('$aiD', '$siD', '$nam', '$tel' )";
should be:
$query = "INSERT INTO myTable (ArchiveID, SessionID, Name, Tel) VALUES ('$aID', '$sID', '$nam', '$tel' )";
and looks like njk updated his answer to reflect this so he should be credited for the answer.

Insert a PHP false into mysql

My MySQL table contains a tinyint(1) value that i use to store a true or false value.
I have the following PHP variables:
$name = '';
$description = '';
$active = true;
Now my SQL query is as follows:
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', $active) ";
This will only work if my value for $active is true. As soon as the active variable is false, php will insert an empty string, instead of a 0 and thus the query will fail.
What is the best method to use false in such a query?
Should i manually convert the false to a '0' string?
Is it better use stings on the PHP side right away? in other words declare: $active = '1';
or can i somehow get PHP to always convert false to a '0' string?
Thanks
Michael
Convert your variable to int:
intval($active)
First of all your values should be escaped using mysql_real_escape_string or mysqli_real_escape_string or other method suitable for your database connection to avoid sql injection then for your specific question regarding false you may do something like that:
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', ".($active?1:0) .")";
or casting $active to int should do the work too:
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', ".((int) $active)).")";
use a mysql_real_escape_string function...
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('".mysql_real_escape_string($name)."', '".mysql_real_escape_string($description)."', ".mysql_real_escape_string (((int) $active))).")";

Categories