Update in two tables at the same time - php

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;
}

Related

Redirect page if PDO database update is success

Here is a part of the code I am using to update the database.
It works, but I would like to redirect the user to another page if the database update is a success.
How can I do that ?
I know the header('Location: ../../');, but where to use it ?
$statement = $dbconnect->prepare("
UPDATE members
SET name = :fname, lastname = :lname, phone = :phone
WHERE member_id = :memberid
");
$dbconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement->execute(
array(
':fname' => "$fname",
':lname' => "$lname",
':phone' => "$phone",
':memberid' => "$memberid"
)
);
} catch(PDOException $e) {
die("ERROR: Could not connect. " . $e->getMessage());
}
Even tried the following, but no redirection
$statement->execute(array(':fname' => "$fname", ':lname' => "$lname", ':phone' => "$phone",':memberid' => "$memberid"));
if ($statement) {
header('Location: http://sitename.com');
} else {
echo 'It failed!';
}
You need to check the result from the PDOStatement::execute execution and use the correct binding when you execute a prepared statement with an array of insert values (named parameters). Note, that the result from the successful PDO::prepare call is a PDOStatement object, not a boolean value.
The folloling script, based on your code, is a possible solution to your problem:
<?php
try {
$dbconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $dbconnect->prepare("
UPDATE members
SET name = :fname, lastname = :lname, phone = :phone
WHERE member_id = :memberid
");
if ($statement === false) {
die("ERROR: Could not prepare statement.");
}
$result = $statement->execute(
array(
':fname' => $fname,
':lname' => $lname,
':phone' => $phone,
':memberid' => $memberid
)
);
if ($result) {
header('Location: http://sitename.com');
exit;
}
} catch(PDOException $e) {
die("ERROR: Could not connect. " . $e->getMessage());
}
?>
If you want to assume that your update was successful as long as you did not encounter any PDO errors (I assume that updates without errors are successful) you can write this:
$statement = $dbconnect->prepare("UPDATE members SET name = :fname, lastname = :lname, phone = :phone WHERE member_id = :memberid");
$dbconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement->execute(array(':fname' => "$fname", ':lname' => "$lname", ':phone' => "$phone",':memberid' => "$memberid"));
// if there were no errors redirect now
header('Location: ../../');
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
On another note outside of dev you should find a different way to handle the error: this is almost the same as not having a try/catch.

No error but data not inserted to database by using PDO

I have a registration form that use PDO to insert the data into database.
This is my html file;
https://codepen.io/anon/pen/pYOKJx
This is my insert.php file
<?php
//insert.php;
if(isset($_POST["cname"]))
{
$connect = new PDO("mysql:host=localhost;dbname=dbname", "testing", "pass");
for($count = 0; $count < count($_POST["cname"]); $count++)
{
$query = "INSERT INTO guest
(cname, sex, ic, age, nationality, phone, e_phone, address, check_in, check_out,remarks)
VALUES (:cname, :sex, :ic, :age, :nationality, :phone, :e_phone, :address, :check_in, :check_out, :remarks)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':cname' => $_POST["cname"][$count],
':sex' => $_POST["sex"][$count],
':ic' => $_POST["ic"][$count],
':age' => $_POST["age"][$count],
':nationality' => $_POST["nationality"][$count],
':phone' => $_POST["phone"][$count],
':e_phone' => $_POST["e_phone"][$count],
':address' => $_POST["address"][$count],
':check_in' => $_POST["check_in"][$count],
':check_out' => $_POST["check_out"][$count],
':remarks' => $_POST["remarks"][$count]
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
echo 'ok';
}
}
?>
I couldn't find any error in error log but when I check my database, the data was not inserted.
What should I change to make it works?
Have you tried changing :
$result = $statement->fetchAll();
if (isset($result)) {
echo 'ok';
}
to
if ($statement->fetchAll()) {
echo 'ok';
}
because it seems that your isset($result) is not executing the command.

Mysql - Get Last inserted ID is not working

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

How to edit multiple rows?

I have tables like this:
-artists
-djs
-track_artist
-track_dj
I am adding two or more artists/djs while adding song via multiple select box. But I couldn't find how to edit those rows.
Adding song function:
$sql = "INSERT INTO sarki (sarki_isim, sarki_tarz, sarki_file, sarki_resim, sarki_eklenmetarihi) VALUES (:isim, :tarz, :file, :resim, NOW())";
$sqlartist = "INSERT INTO trackartist (trackartist_artist, trackartist_track) VALUES (:artistid, :trackid)";
$sqldj = "INSERT INTO trackdj (trackdj_dj, trackdj_track) VALUES (:djid, :trackid)";
try {
$stmt = $this->db->prepare($sql);
$stmt->execute(array(':isim' => $b["isim"], ':tarz' => $b["tarz"], ':file' => $b["file"], ':resim' => $b["resim"]));
$trackid = $this->db->lastInsertId();
foreach ($b["artists"] as $artist) {
$insert = $this->db->prepare($sqlartist);
$insert->execute(array(":artistid" => $artist, ":trackid" => $trackid));
}
foreach ($b["djs"] as $artist) {
$insert = $this->db->prepare($sqldj);
$insert->execute(array(":djid" => $artist, ":trackid" => $trackid));
}
$db = null;
return $stmt;
} catch (PDOException $e) {
echo $e->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.

Categories