How to edit multiple rows? - php

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

Related

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.

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.

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

Variables not being saved to database in PHP

I'm having an issue with a piece of my code. It works perfectly fine, except it won't save itself to the database. This is the code:
function createOrder($user, $cart, $price, $method) {
try {
$username = "root";
$password = "";
$connection = new PDO('mysql:host=localhost;dbname=dreamlineslaapsystemen', $username, $password);
$connection->beginTransaction();
$productList=$_SESSION['products'];
$orderList=$_SESSION['orders'];
$orderItems=$_SESSION['orderitems'];
$orderid = generateOrderid();
$allOrders = array();
for($i=0; $i<count($orderList); $i++) {
array_push($allOrders, $orderList[$i]->getID());
}
while(in_array($orderid, $allOrders)) {
$orderid = generateOrderid();
}
$today = date("Y-m-d H:i:s");
$order = new Order($orderid, $user->getID(), $price, $today, $method);
$newOrder = array(
':id' => $orderid,
':userid' => $user->getID(),
':date' => $today,
':method' => $method
);
$addOrder = $connection->prepare('INSERT INTO orders(id, userid, date) VALUES (:id, :userid, :date, :method');
$addOrder->execute($newOrder);
array_push($orderList, $order);
foreach($cart->getCart() as $item => $amount) {
$itemid=null;
for($i=0; $i<count($productList);$i++) {
if($productList[$i]->getID()==$item) {
$orderitem = new Orderitem($orderid, $i, $amount);
array_push($orderItems, $orderitem);
$newOrderitem = array(
':orderid' => $orderid,
':productid' => $i,
':amount' => $amount
);
$addOrderitem = $connection->prepare('INSERT INTO orderitems(orderid, productid, amount) VALUES (:orderid, :productid, :amount');
$addOrderitem->execute($newOrderitem);
}
}
}
$connection->commit();
$_SESSION['orders']=$orderList;
$_SESSION['orderitems']=$orderItems;
return $orderid;
} catch(PDOException $e) {
$connection->rollback();
print "Er is iets fout gegaan: " . $e->getMessage() . "<br>";
return null;
}
}
It does add everything to the arrays and sessions and when I do var_dump to see if it is all stored correctly in the sessions/arrays. It just won't add to the database.
You have 3 columns yet you are inserting 4 values. I assume you have a method column in your table and your insert statements lacks closing ) parenthesis.
$addOrderitem = $connection->prepare('INSERT INTO orderitems(orderid, productid, amount, method) VALUES (:orderid, :productid, :amount, :method'));
$addOrderitem = $connection->prepare('INSERT INTO orderitems(orderid, productid, amount) VALUES (:orderid, :productid, :amount'));

Categories