Using select last_insert_id() from php not working - php

I have this exact same issue, but that answer is old, and I've read other places the use of mysql_insert_id() is depreciated and should be avoided in new code.
The database is InnoDB and the primary key for this table is set to auto_increment.
Can anyone see what I'm doing wrong here? I should note I'm a beginner and learning on my own, so I apologize is this is glaringly obvious.
$query = "INSERT INTO VENUES (province,city,venue)" . "VALUES " . "('$province','$city','$venue')";
$result = $db->query($query);
if ($result) {
echo "$result row(s) sucessfully inserted.<br/>";
} else {
echo "$db->error<br/>";
}
$result = $db->query("select last_insert_id()");
echo $result->num_rows //returns 1
echo $result; //nothing beyond this line happens
UPDATE: I am using mysqli.

The correct way to get the last inserted id, when using mysql_* is to make a call to mysql_insert_id().
What you are reading is partially correct - mysql_insert_id is in the process of being deprecated, but it's not just that function. All mysql_* functions are being deprecated. Instead you should use either PDO or mysqli_*.
In your code snippet, it is unclear which database access library you are using. Since your calls seem to be bound to an object, it is likely you are using PDO or mysqli.
For PDO you can use PDO::lastInsertId.
For mysqli, use mysqli->insert_id.

Related

php mysql get id of last insert row giving error

i want to get the id of last inserted row and i m using mysql_insert_id() function. but giving issue
here is my code :
if($i == 0)
{
$query = "update events set e_did ='".$multi_event."' where eid = '".$display_id."'";
mysqli_query($con,$query);
file_put_contents('log.txt', mysql_insert_id(), FILE_APPEND);
}
else
{
$query = "INSERT INTO events (start_date, end_date, text, rec_type, event_pid, event_length, e_did) VALUES ('".$row['start_date']."','".$row['end_date']."','".$row['text']."','".$row['rec_type']."','".$row['event_pid']."','".$row['event_length']."','".$multi_event."')";
mysqli_query($con,$query);
file_put_contents('log.txt', 'A'.mysql_insert_id().'A', FILE_APPEND);
}
now both time i m getting same id. what is the issue. is i m doing wrong something somewhere ?
If you use the mysqli functions, you must use mysqli_insert_id. You can't mix ext/mysql and ext/mysqli.
Also, UPDATE does not generate a new auto-increment id. You should call mysqli_insert_id() after INSERT, but not UPDATE.
mysqli_insert_id() only returns an id for INSERT queries. An update query will NOT return an id, because by definition you must already have a row in the database for it be getting updated.
With UPDATE, you are editing records, not adding ones. So no new IDs are generated. You can only use mysql_insert_id on INSERT.
Note: mysql_* functions are deprecated and won't be supported in future versions. You should be using either mysqli_* or PDO.

mysql_insert_id() echos 0

I am not the first to have this problem but the solutions of the others don't work.
This script always returns 0 for mysql_insert_id(); I am using multiple primary keys.
$sql = "INSERT INTO Produkte (Name,Price,Description,User)
VALUES ('".$_POST['name']."','".$_POST['price']."','".$_POST['description']."','".$_SESSION['user']."');";
$result = $GLOBALS['DB']->query($sql);
echo mysql_insert_id();
echo '<div class="saving">';
if($result){
echo "Saved!";
} else{
echo("Saving failed");
} echo '</div>';
}
I already tried mysql_insert_id($link), where I linked $link to a mysql_connect() and mysql_insert_id($GLOBALS['DB']->MySQLiObj)
My $GLOBAL['DB']
if(!isset($GLOBALS['DB']))$DB = new \System\Database\MySQL(MYSQL_HOST,MYSQL_BENUTZER,MYSQL_KENNWORT,MYSQL_DATENBANK,MYSQL_PORT);
My MySQL class:
public $MySQLiObj = null;
function __construct($server, $user, $password, $db, $port = '3306')
{
$this->MySQLiObj = new \mysqli($server, $user, $password, $db, $port);
if (mysqli_connect_errno())
{
echo "Keine Verbindung zum MySQL-Server möglich.";
trigger_error("MySQL-Connection-Error", E_USER_ERROR);
die();
}
$this->query("SET NAMES utf8");
}
The documentation for mysql_insert_id() explains this very well:
The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
It is possible that your table does not have any column set to AUTO_INCREMENT. mysql_insert_id() will return 0 in such cases.
Usual disclaimer: mysql_ functions are deprecated and are soon to be removed. Stop using them and switch to MySQLi / PDO instead.
Your query is failing because you are using the reserved keyword desc without ticks. As a result the INSERT fails and thus no ID is returned.
$sql = "INSERT INTO Produkte (Name,Price,Desc,User)
VALUES ('".$_POST['name']."','".$_POST['price']."','".$_POST['description']."','".$_SESSION['user']."');";
should be
$sql = "INSERT INTO Produkte (Name,Price,`Desc`,User)
VALUES ('".$_POST['name']."','".$_POST['price']."','".$_POST['description']."','".$_SESSION['user']."');";
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You are also wide open to SQL injections
The core problem here is that you're using mysqli for your query() call, but then trying to use the mysql_insert_id() function.
Please note that the mysqli and mysql functions are two entirely separate libraries, and are incompatible with each other.
If you're using mysqli in one part of your code, you must use mysqli for all other DB-related code as well, otherwise they will not work together.
So you must use the mysqli::$insert_id property instead.
You mentioned in the question that you can access your connection object as $GLOBALS['DB']->connection. In that case, you should be able to write your code as follows:
$newId = $GLOBALS['DB']->connection->insert_id;
I hope that helps.
PS: While I'm here, I'll add that you should avoid putting $_POST variables directly into your query string like that. It's very poor practice and has some dangerous security implications. You should look into using mysqli->prepare() and mysqli->bind_param() to add the parameters for your queries instead.
If you are using phpMyAdmin, maybe PersistentConnections is disabled in the config file (config.inc.php).
If this is the case, change it to:
$cfg['PersistentConnections'] = TRUE;
desc is a reserved word in mysql, so you need escape it with ``
INSERT INTO Produkte (Name,Price,`Desc`,User)
list of reserved words
mutliple errors i guess :
mysqli_insert_id($con) //$con is connection obj
Sql query : extra semi-colon in sql-query end and reserved keyword DESC used
"INSERT INTO Produkte (Name,Price,`Desc`,User)
VALUES ('".$_POST['name']."','".$_POST['price']."','".$_POST['description']."','".$_SESSION['user']."')";
Refer manual :
http://us3.php.net/manual/en/mysqli.insert-id.php
OK I finally made it!
In my Class I added the function insert_id() and then added the insert_id variable locally.
public function insert_id()
{
$result = $this->MySQLiObj->insert_id;
return $result;
}

PHP Retrieve Database Value

So i have this so far..
if(isset($_POST['Decrypt']))
{
$dbinary = strtoupper($_POST['user2']);
$sqlvalue = "SELECT `value` FROM `license` WHERE `binary` = '$dbinary'";
$dvalue = mysql_query($sqlvalue) or die(mysql_error());
}
I have a field where the user enters a binary code which was encrypted. (The encrypt part works). This is supposed to retrieve the value from the database. When ever i do it, instead of the value showing up, it says "Resource id #11".
There's nothing wrong with your quoting. In fact, everything looks right so far.
The thing is, right now $dvalue is just a resource to the SQL database. You have to fetch the contents with one more line:
$dvalue = mysql_fetch_array($dvalue);
In the future, you might want to start using PDO or MySQLi instead of the mysql functions, because those are deprecated as of 5.5.0. The advantage of PDO and MySQLi is that they offer security from SQL Injection, which is when users run their own SQL code by inputting something like x'; DROP TABLE members; --.
Don't use the mysql_ functions anymore. They are deprecated. Use PDO or MySQLi instead.
That being said, you are only running the query, and not retrieving any results. You will have to call a function like mysqli_fetch_array to get data from the resource ID that mysqli_query will return.
My advice is to go back to the tutorials and documentation and try again with one of these other extensions. Good luck.
Read this page: W3 Schools page on MySQL select useage. Basically $dvalue is a result set id and you'll need to actually fetch the array out of the database in another step. Also, mysql_* functions are deprecated. Lookup and use the mysqli_* functions instead.
while($row = mysqli_fetch_array($dvalue))
{
echo $row['value'];
echo "<br>";
}

MySQL query to PDO

I've been suggested to migrate from the deprecated MySQL to MySQLi or PDO, I finally got around to it as it'll help my project without wasting too much time. I've been reading a lot on some great articles and websites, but I'd like the best suggestion on how to fetch array with PDO, I can do it with a while loop but I dislike it, how would I convert this current code to PDO.
public function User_Details($_iD){
$_iD = mysql_real_escape_string($_iD);
$query="SELECT _iD,_iPassword,_iEmail,_iNickname,_iUsername,_iProfilePicture,_iFriendCount FROM users WHERE _iD='$_iD' AND _iStatus='1'";
$result = mysql_query($query) or die(mysql_error());
$data = mysql_fetch_array($result) or die(mysql_error());
return $data;
}
I am able with a while loop but as I said, that's not what I'm interested in unless it's a better option.
PDO :
$sql = "SELECT _iD,_iPassword,_iEmail,_iNickname,_iUsername,_iProfilePicture,_iFriendCount FROM users WHERE _iStatus='1'";
foreach ($db->query($sql) as $row){
print $row['_iD'] .' - '. $row['_iUsername'] . '<br />';
}
It would also be wise to actually study how PDO is different from old methods instead of trying it the old way with new tools. One of the things that PDO offers is to create prepared statements, which you can execute, and fetch in various ways. I think the fetchAll method is exactly what you are looking for.

mysql_real_escape_string(); problems

I seem to be having a small problem with mysql_real_escape_string();
Its not giving me a return value, for example i am using it like this:
$a = mysql_real_escape_string($tableName);
but $a is blank.
I have run several tests like so:
$query = "CREATE TABLE ".$tableName." AS (SELECT * FROM availability WHERE 1=2)";
echo "query: " . $query;
echo "tableName: " . $a;
and the output is as follows:
query: CREATE TABLE gRLEFCnOauUlJAekIEq5 AS (SELECT * FROM availability WHERE 1=2)tableName:
As you can see the query is as expected, but the the $a shows nothing.
Any Ideas?
mysql_real_escape_string requires an active connection to the database. You will need to connect to the database with mysql_connect() for it to work.
However, it would be better to switch to PDO or MySQLi and use a prepared statement because:
The mysql_* library is deprecated.
A prepared statement is better than escaping.
In order for mysql_real_escape_string to work, you must have an active database connection. If you cannot have a database connection, then use mysql_escape_string instead.
Side note: neither one of these is ideal, as the mysql extension is deprecated. You should move towards PDO or mysqli.

Categories