Call to undefined method PDO::last_Insert_Id() [duplicate] - mysql

This question already has answers here:
PDO get the last ID inserted
(3 answers)
Closed 2 years ago.
I'm getting an error message: Call to undefined method PDO::last_Insert_Id()
Here's my code:
$testcode = $conn -> prepare("INSERT INTO tblCategory
(Category, DisplayOrder)
VALUES('Test', 0)");
try {
$testcode ->execute();
$ID = $conn->last_Insert_Id();
}
catch (PDOException $e)
{echo $e->getMessage();
}
var_dump($conn instance of PDO) returns bool(true) so $conn is the PDO connection.
How do I correct so I don't get the error? I do need that last inserted id. Thanks.

This PDO method is called lastInsertId(), not last_Insert_Id().
So:
$ID = $conn->lastInsertId();

Related

How to get fields from db in codeigniter

I am using mysqli_num_fields() but facing error
I also used mysql_num_fields but again faced error.
$this->db->select('*');
$this->db->from('quizmarks');
$query = $this->db->get();
$data= $query->result();
echo mysqli_num_fields($data);
exit();
Here is the error
A PHP Error was encountered
Severity: Warning
Message: mysqli_num_fields() expects parameter 1 to be mysqli_result, array given
$query = $this->db->get('quizmarks');
return $query->num_fields();
More optimal solution
Use directly get method becoz you need all fields of that table

PHP Get JSON & Insert Into DB Via PDO [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
My PHP Code:
<?php
$host = ""; $db_name = ""; $username = ""; $password = "";
try {
$conn = new PDO("mysql:host=".$host.";dbname=".$db_name, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$json = file_get_contents('');
$obj = json_decode($json, TRUE);
$stmt = $conn->prepare("INSERT INTO item_details (item_id,value,circulation) VALUES (:item_id,:value,:circulation");
foreach($obj['items'] as $key => $index) {
$item_id = $key;
$value = $index['value'];
$circulation = $index['circulation'];
$stmt->bindparam(":item_id", $item_id);
$stmt->bindparam(":value", $value);
$stmt->bindparam(":circulation", $circulation);
$stmt->execute();
}
?>
Problem:
I've tested via echoing the data to the page within my loop and the data is being retrieved, however no information is being submitted to my database.
Questions:
How can I improve upon my script to add relevant debugging lines to
find the cause?
Is it obvious why my script does not work? If so, could you please explain this however my above question will aid my learning curve with future development!
Catalin Minovici is correct about bindParam however PDO errors are not always thrown exceptions that can be caught, so a try/catch is only helpful here if you are going to check the PDO errors, and throw your own exception.
You have missed a parenthesis in your query preparation.
// missing paren...........................................................................................here: v
$stmt = $conn->prepare("INSERT INTO item_details (item_id,value,circulation) VALUES (:item_id,:value,:circulation)");
See the documentation for reading PDO query errors after your execute() on php.net
Additionally it is better to combine all of the results into a single insert operation, rather than executing a new insert on each iteration of the loop.
You forgot closing bracket in values:
prepare("INSERT INTO item_details (item_id,value,circulation) VALUES (:item_id,:value,:circulation)");

Why am I getting error SQLSTATE[HY093]: Invalid parameter number: ? How can I fix it?

Based on this question How to insert array into mysql using PDO and bindParam?
I'm trying to insert values of an array into mysql via PDO.
I'm having a hard time of it, because I keep getting the following error.
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
for this line $stmt->execute();
I'm guessing the problem has something to do with this line
$stmt->bindParam(':val$count', $val,PDO::PARAM_STR); Specifically 'val$count', but I'm not sure exactly what is going wrong.
QUESTION: What am I doing wrong? How can I fix this?
Anyway here is the code I'm using along with the sample array.
$lastInsertValue=87;
$qid[0][0]=1;
$qid[0][1]=1;
$qid[1][0]=2;
$qid[1][1]="null";
$qid[2][0]=3;
$qid[2][1]=0;
$array_count = count($qid);
if (isset($lastInsertValue))
{
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stqid=array();
$a=0;
for ($i=0; $i<$array_count; $i++)
{
$stqid[$a]=$lastInsertValue;
$a++;
$stqid[$a]=$qid[$i][0];
$a++;
$stqid[$a]=$qid[$i][1];
$a++;
}
$sql = "INSERT INTO qresults (instance, qid, result) VALUES ( :val0, :val1, :val2)";
$count = 0;
$stmt = $dbh->prepare($sql);
foreach ($stqid as $val)
{
$stmt->bindParam(':val$count', $val,PDO::PARAM_STR);
$count++;
}
$stmt->execute();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Yikes, so many issues.
Your array building is so verbose. Try this
$stqid = array();
foreach ($qid as $qidArr) {
$stqid[] = $lastInsertValue; // no idea why you repeat this
$stqid[] = $qidArr[0];
$stqid[] = $qidArr[1];
}
Use positional placeholders if you're simply relying on number of arguments
$sql = 'INSERT INTO ... VALUES (?, ?, ?)';
bindParam uses references which you are overwriting with each loop iteration. You would want to use bindValue() instead
Your query only has 3 placeholders but your $stqid array has 9 items. This is the source of your error.
You have single quotes around a variable, which will be treated as the variable name $count (not the value), try concatenating the variable to the string. Give this a try:
$stmt->bindParam(':val' . $count, $val,PDO::PARAM_STR);
for ($i=0; $i<$array_count; $i++)
{
$stqid[$a]=$lastInsertValue;
$a++;
$stqid[$a]=$qid[$i][0];
$a++;
$stqid[$a]=$qid[$i][1];
$a++;
}
so in case $i = 2, it will add $stqid[6], $stqid[7], $stqid[8] so
foreach ($stqid as $val)
{
$stmt->bindParam(':val$count', $val,PDO::PARAM_STR);
$count++;
}
will give you :val0 to :val8
In your query you have only :val0 to :val2.
Also having multiple values in one field in database is bad. Don't do it. Try to redesign your DB differently
EDIT: bad math in the morning... sorry

mysql_query returning boolean or string?

For some reason when I run a $result=mysql_query(...) that should return an array to be parsed with mysql_fetch_array, I keep getting an error that the value returned for $result is either a string or boolean, which mysql_fetch_array() can't work with. I've been running the same query on my server for years and for some reason it stopped working recently.
here's the sample code:
$result=mysql_query("SELECT * FROM `patient_list`");
while ($row=mysql_fetch_array($result)) {
...
}
I recently upgraded to the newest version of wamp. might that have anything to do with it? Any thoughts?
This error means taht result of mysql_query is not valid.Please place
echo mysql_error();
after you call mysql_query
Your problem could be access / database doesn't exist / anything
Always check the query runs correctly execute your query like this :
$result = mysql_query(<query>);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// process the result here
Documentation for mysql_query
Try this:
$result = mysql_query("SELECT * FROM `patient_list`") or die( mysql_error() );

Invalid PDO query does not return an error

The second SQL statement below returns an error in phpMyAdmin:
SET #num=2000040;
INSERT INTO artikel( artikel_nr, lieferant_nr, bezeichnung_1, bezeichnung_1 )
SELECT #num := #num +1 AS anum, 70338, f2, f3
FROM import
WHERE id >1
MySQL says:
#1110 - Column 'bezeichnung_1' specified twice
All correct. But when I run the queries in Symfony 1.4 with this function:
// run sql query
// http://erisds.co.uk/symfony/snippet-creating-debugging-complex-sql-queries-in-symfony
// http://stackoverflow.com/questions/5434702/php-quick-refactoring
// param $sql: the query to run
// param $silent: bool if errors should be ignored
// throws: pdo error info if statement failed and $silent=false
// returns: pdo-statement (use for looping over result rows and error messages)
public static function runQuery($sql, $silent=false)
{
$conn = Propel::getConnection();
$pdo_statement = $conn->prepare($sql);
$error = null;
try
{
$pdo_statement->execute();
}
catch (Exception $e)
{
$error = $e->getMessage();
}
if ( !$error )
{
$pdo_error = $pdo_statement->errorInfo();
$error = $pdo_error[2];
}
if ( !$silent && $error ) throw new Exception($error);
return $pdo_statement;
}
no error is thrown. The two SQL statements must be submitted at the same time since they depend on each other. The faulty query is constructed from user input. I need to get that error back, otherwise I can't tell if the database was changed, and I can't tell the user about it.
Do you know why PDO doesn't complain about the invalid statement, and if it can't be made to do so, how to get the success/failure information?
BTW the query does update the database if there are no duplicate columns.
Here's the link to the PDOStatement class: http://www.php.net/manual/en/class.pdostatement.php
This is expected behavior. Since there are two statements and the first one is valid, you have to use nextRowset()
try
{
$pdo_statement->execute();
while ($pdo_statement->nextRowset()) {/* https://bugs.php.net/bug.php?id=61613 */};
}
Source: bugs.php.net/bug.php?id=61613
By default PDOStatement::execute() doesn't throw any exception, it simply returns false on error. You have to set error handling to PDO::ERRMODE_EXCEPTION through db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION).
If you have the option to use mysqli instead of PDO for the multi query, you can use mysqli_multi_query. As error handling is a little complex, here is my function:
/**
* Executes multiple queries at once (separated by semicolons) and discards the results
*
* #param string $sql
* #throws RuntimeException if a query failed
*/
function multi_query($sql) {
$mysqli = new mysqli('host', 'user', 'password', 'database');
//Execute all queries
$index = 1;
if ($mysqli->multi_query($sql)) {
do {
// next_result() fails if store_result() is not called
if ($result = $mysqli->store_result()) {
$result->free();
}
$has_next = $mysqli->more_results();
if (!$has_next)
return; // all queries successfully executed
$index++;
} while ($mysqli->next_result());
}
// At this point, either the multi_query() has returned false - which is
// when the first query failed - or more_results() was true, while next_result()
// returned false - which is when a different query failed.
$error = $mysqli->error;
if (!$error)
$error = $mysqli->errno ? "errno $mysqli->errno" : '(unknown error)';
throw new RuntimeException("mysqli query $index failed: $error");
}