Mysql - Get Last inserted ID is not working - php

I dont know why this is not working. The LAST_INSERT_ID() is not being catched, can someone help me please?
$query = "
INSERT INTO products_categories (
name,
url
) VALUES (
:name,
:url
) SELECT LAST_INSERT_ID();
";
$query_params = array(
':name' => $_POST['name'],
':url' => $_POST['url']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
echo 0;
return true;
}
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$id_category = $result["id"];

"You can remove your SELECT LAST_INSERT_ID() part from the query and use $db->lastInsertId(); instead." - #barell

Try this;
<?php
$query = "
INSERT INTO products_categories (
name,
url
) VALUES (
:name,
:url
)
";
$query_params = array(
':name' => $_POST['name'],
':url' => $_POST['url']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
echo 0;
return true;
}
$result = $stmt->fetch(PDO::FETCH_ASSOC);
//$id_category = $result["id"];
$id_category = $db->lastInsertId();
Hope it helps

Related

foreach loop update only last value three times in table

This is a code to update a table with foreach loop. But it update the last value three times which is POST[s3_name]
<?php
$names = [$_POST['s1_name'], $_POST['s2_name'], $_POST['s3_name']];
$query = "update students SET Name=:Name WHERE ProjectID='$id'";
foreach ($names as $name) {
try
{
$stmt = $conn->prepare($query);
$stmt->bindParam(':Name', $name);
$result = $stmt->execute();
$msg = "Record updated";
}
catch(PDOException $ex)
{
$msg = $ex -> getMessage();
}
}
You could get the id from somewhere and loop that as well. Something like this
$names = [
['id' => 1, 'name' => 'name1'],
['id' => 2, 'name' => 'name2'],
['id' => 3, 'name' => 'name3']
];
foreach ($names as $name) {
try {
$query = "update students SET Name=:Name WHERE ProjectID=:Id";
$stmt = $conn->prepare($query);
$stmt->bindParam(':Name', $name['name']);
$stmt->bindParam(':Id', $name['id']);
$result = $stmt->execute();
$msg = "Record updated";
} catch(PDOException $ex) {
$msg = $ex -> getMessage();
}
}

How to insert an array into SQL using PHP?

I have an array like:
$arrays = array(
array('id' => '1','Name' => 'Monica','online' => '1'),
array('id' => '2','Name' => 'Jessica','online' => '1')
);
I only included 2, but let's say I have 200 of these. I already have a table in SQL with associated columns id, name and online.
Can you help me input these into database? I'm developing using wordpress. From Insert array into MySQL database with PHP I have an idea of how to do it for 1 single array
If you're having an array , you need to use a foreach loop to know the length content of insertion.
This is an example of insertion:
if(is_array($array)){
$sql = "INSERT INTO some_table (id, name, online) values ";
$valuesArr = array();
foreach($array as $row){
$id= (int) $row['id'];
$email = mysql_real_escape_string( $row['name'] );
$name = mysql_real_escape_string( $row['online'] );
$valuesArr[] = "('$id', '$email', '$name')";
}
$sql .= implode(',', $valuesArr);
mysql_query($sql) or exit(mysql_error());
}
Please try this.
Using PDO example
$sql = <<<EOT
INSERT IGNORE INTO
table_name (id, name, online)
VALUES
(:id, :name, :online)
;
EOT;
define("INSERT_UPDATE_SQL", $sql,true);
try{
$con = new PDO(CONNECTION_STRING);
if(is_array($arrays)){
$stmt = $con->prepare(INSERT_UPDATE_SQL);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':online', $online);
foreach($arrays as $row){
$id = (int)$row['id'];
$name = $row['Name'];
$online = $row['online'];
$stmt->execute();
}
$stmt = null;
}
$con = null;
}catch (PDOException $e) {
echo 'error !!';
throw $e;
}
not changed if already registered.

can't print single item in a array

I don't know what's going on here.
I have this piece of code.
$data = getDataBySession($_COOKIE["session"],$db);
echo $data['name'];
print_r($data);
?>
function.php
function getDataBySession($session, PDO $db){
$query = "SELECT name,
lastname
FROM users
WHERE cookie = :id
";
$query_params = array(
':id' => $session
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
echo "Error > " .$ex->getMessage();
}
$dataUser = $stmt->fetchAll();
return $dataUser;
}
print_r return this: Array ( [0] => Array ( [name] => JOSE [lastname] => SUAREZ ) )
But echo can't show it's content, nor print.
I don't belive it's the function because it returns the array, as you can see.
What am i doing wrong?

Update in two tables at the same time

Is there a way to update two tables at the same time? I have a table food and table food_r
This is the code with which I insert into food
$rest_id = null;
if ( !empty($_GET['rest_id']))
{
$rest_id = $_REQUEST['rest_id'];
}
if ( null==$rest_id )
{
echo "null==$rest_id";
}
if(isSet($_POST['submit']))
{
// keep track post values
$food_name = $_POST['food_name'];
$food_description = $_POST['food_description'];
$food_menu = $rest_id;
$usertype = $_SESSION['usertype'];
// update data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $pdo->prepare("INSERT INTO food ( food_name, food_description, food_menu, usertype )
VALUES (:food_name, :food_description, :food_menu, :usertype)");
$sql->execute(array(
':food_name' => $food_name,
':food_description' => $food_description,
':food_menu' => $food_id,
':usertype' => $_SESSION['usertype']
));
Database::disconnect();
echo "Product added!";
}
Now If I want to be visible the inserted product I must insert in table food_r value of food_menu and the value of usertype.
How can I do this?
Update: It's working that way. Thank's to #JonathonWisnoski for pointing me to transactions..
$pdo->beginTransaction();
$sql = $pdo->prepare("INSERT INTO food ( food_name, food_description, food_menu, usertype )
VALUES (:food_name, :food_description, :food_menu, :usertype)");
$sql->execute(array(
':food_name' => $food_name,
':food_description' => $food_description,
':food_menu' => $rest_id,
':usertype' => $_SESSION['usertype']
));
$lastInsertID = $pdo->lastInsertId();
$sql = $pdo->prepare("INSERT INTO food_r (food_id, usertype)
VALUES (:rest_id, :usertype)");
$sql->execute(array(
':rest_id' => $lastInsertID,
':usertype' => $rest_id
));
$pdo->commit();
Update: It's working that way. Thank's to #JonathonWisnoski for pointing me to transactions..
I've also put try{}catch{} block for any errors.
try
{
$pdo->beginTransaction();
$sql = $pdo->prepare("INSERT INTO food ( food_name, food_description, food_menu, usertype )
VALUES (:food_name, :food_description, :food_menu, :usertype)");
$sql->execute(array(
':food_name' => $food_name,
':food_description' => $food_description,
':food_menu' => $rest_id,
':usertype' => $_SESSION['usertype']
));
$lastInsertID = $pdo->lastInsertId();
$sql = $pdo->prepare("INSERT INTO food_r (food_id, usertype)
VALUES (:rest_id, :usertype)");
$sql->execute(array(
':rest_id' => $lastInsertID,
':usertype' => $rest_id
));
$pdo->commit();
}
// any errors from the above database queries will be catched
catch (PDOException $e)
{
// roll back transaction
$pdo->rollback();
// log any errors to file
ExceptionErrorHandler($e);
exit;
}

invalid parameter number exception using named parameter

I am getting "invalid parameter number:parameter undefined" exception when attempting an insert query to mysql database.
I am returning the result to my Android app as json.
if (!empty($_POST))
{
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:fromm,:too,:ccode,:stud,:rmk ) ";
$query_params = array(
':dat' => $_POST['datee'],
':from'=>$_POST['fromm'],
':to'=>$_POST['too'],
':ccode'=>$_POST['course'],
':stud'=>$_POST['sname'],
':rmk'=>$_POST['remark'],
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = $ex->getMessage();
$response["date"] = $_POST['datee'];
$response["from"] = $_POST['fromm'];
$response["to"] = $_POST['too'];
$response["ccode"] = $_POST['course'];
$response["stud"] = $_POST['sname'];
$response["remark"] = $_POST['remark'];
die(json_encode($response));
}
}
you lack a m in
':from'=>$_POST['fromm'],
should be
':fromm'=>$_POST['fromm'],
you must be careful when using named parameter, I myself am very prone to making such errors
that's why I more easily use the ? placeholder, this way in your exemple:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (?,?,?,?,?,?) ";
$query_params = array(
$_POST['datee'],
$_POST['fromm'],
$_POST['too'],
$_POST['course'],
$_POST['sname'],
$_POST['remark'],
);
then:
$result = $stmt->execute($query_params);
you must be sure that the params are in good order (same as in query)
In your query, you're misspelling from:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:fromm,:too,:ccode,:stud,:rmk ) ";
Replace it with:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:from,:too,:ccode,:stud,:rmk ) ";

Categories