How to bind PHP prepare and execute statement properly? - php

I have a function that inserts or updates a value in the database.
I am using a prepare and execute statement and I want to match my function's ELSE-clause to match the prepared statement.
In my ELSE-clause I have one more value (i.e. $id), so I'm not sure if I can assign it in the execute array.
function insert_value($item_name, $description, $supplier_code, $cost, $sell_price,$num_on_hand, $reorder_point, $back_order, $id=0)
{
$connection = db_connect();
if($id==0)
{
$sql = 'INSERT INTO inventory (itemName, description, supplierCode, cost, price, onHand, reorderPoint, backOrder)
VALUES(:itemName, :description, :supplierCode, :cost, :price, :onHand, :reorderPoint, :backOrder);';
}
else
{
//NEED TO CHANGE THIS PART
$sql = "UPDATE inventory SET itemName='$item_name', description='$description', supplierCode='$supplier_code',
cost='$cost', price='$sell_price', onHand='$num_on_hand', reorderPoint='$reorder_point', backOrder='$back_order'
WHERE id='$id'";
}
$prepare = $connection->prepare($sql);
$prepare->execute(array( // AND THIS PART
":itemName" => $item_name,
":description" => $description,
":supplierCode" => $supplier_code,
":cost" => $cost,
":price" => $sell_price,
":onHand" => $num_on_hand,
":reorderPoint" => $reorder_point,
":backOrder" => $back_order,
));
}

Something like:
function insert_value($item_name, $description, $supplier_code, $cost, $sell_price,$num_on_hand, $reorder_point, $back_order, $id=0){
$connection = db_connect();
$arr = array(":itemName" => $item_name,
":description" => $description,
":supplierCode" => $supplier_code,
":cost" => $cost,
":price" => $sell_price,
":onHand" => $num_on_hand,
":reorderPoint" => $reorder_point,
":backOrder" => $back_order);
if($id==0){
$sql = 'INSERT INTO inventory (itemName, description, supplierCode, cost, price, onHand, reorderPoint, backOrder)
VALUES(:itemName, :description, :supplierCode, :cost, :price, :onHand, :reorderPoint, :backOrder)';
}else{
$sql = "UPDATE inventory SET itemName=:itemName, description=:description, supplierCode=:supplierCode,
cost=:cost, price=:price, onHand=:onHand, reorderPoint=:reorderPoint, backOrder=:backOrder
WHERE id=:id";
$arr[":id"] = $id;
}
$prepare = $connection->prepare($sql);
$prepare->execute($arr);
}
Also you might want to check (if you don't do this already) to see if $connection is valid otherwise you might get errors once it gets to prepare/execute.

Related

Get last ID on CRUD [duplicate]

$query = "INSERT INTO news VALUES (NULL, :param1 , :param2 )";
$stmt = $pdo->prepare($query);
$params = array(
"param1" => $p['title'],
"param2" => $p['body'],
);
$data = $stmt->execute($params);
// here i would like get current inserted ID. Is possible?
$id = $data->id ???? ;
How can i make this?
$query = "INSERT INTO news VALUES (NULL, :param1 , :param2 )";
$stmt = $pdo->prepare($query);
$params = array(
"param1" => $p['title'],
"param2" => $p['body'],
);
$data = $stmt->execute($params);
so you can do like this to get last inserted Id
$last_id = $pdo->lastInsertId();
Use :
$last_insert_id = $pdo->lastInsertId();
You could use PDO::lastInsertId
$last_insert_id = $pdo->lastInsertId();

Query conditions to insert data from a form

What I'm trying to do is:
If the age input in my form = 28, 30, 25 or 21 then I want to auto insert value 8 in the column (VE), else keep it empty. Is this the right way to do that?
if($form_data->action == 'Insert')
{
$age=array(28, 30, 25, 21);
$age_str=implode("','", $age);
if($form_data->age == $age_str){
$query="INSERT INTO tbl
(VE) VALUE ('8') WHERE id= '".$form_data->id."'
";
$statement = $connect->prepare($query);
$statement->execute();
}
$data = array(
':date' => $date,
':first_name' => $first_name,
':last_name' => $last_name,
':age' => $age
);
$query = "
INSERT INTO tbl
(date, first_name, last_name, age) VALUES
(:date, :first_name, :last_name, :age)
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
$message = 'Data Inserted';
}
}
Also, how do I insert the new row with the row id from the other form data going into tbl?
Use php's in_array instead of trying to compare a string. To get the id of the query where you insert the form data, you can return the id of the insert row from your prepared statement.
if ($form_data->action == 'Insert') {
// assuming $age, $date, $first_name, $last_name
// already declared prior to this block
$data = array(
':date' => $date,
':first_name' => $first_name,
':last_name' => $last_name,
':age' => $age
);
$query = "
INSERT INTO tbl
(date, first_name, last_name, age) VALUES
(:date, :first_name, :last_name, :age)
";
$statement = $connect->prepare($query);
if ($statement->execute($data)) {
$message = 'Data Inserted';
// $id is the last inserted id for (tbl)
$id = $connect->lastInsertID();
// NOW you can insert your child row in the other table
$ages_to_insert = array(28, 30, 25, 21);
// in_array uses your array...so you don't need
// if($form_data->age == $age_str){
if (in_array($form_data->age, $ages_to_insert)) {
$query="UPDATE tbl SER VE = '8' WHERE id= '".$id."'";
$statement2 = $connect->prepare($query);
$statement2->execute();
}
}
}

INSERT INTO table VALUES - mysql_query to PDO

trying to insert values from an old mysql_query using the new PDO and can't seem to get it. Here's the old code that works with the old method:
$query = mysql_query("INSERT INTO videos VALUES ('','$title',time(),'0','$length','','$name','$cat','$reciter','$genre')");
I've tried variations of the following code taken from another question on stack, but nothing that works for me.
$query = "UPDATE people
SET price=?,
contact=?,
fname=?,
lname=?
WHERE id=? AND
username=?";
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $price);
$stmt->bindParam(2, $contact);
$stmt->bindParam(3, $fname);
$stmt->bindParam(4, $lname);
$stmt->bindParam(5, $id);
$stmt->bindParam(6, $username);
$stmt->execute();
the first value to be inserted is an auto increment value in the db. I am at a loss as to how to write that with the new PDO. Then the third is an attempt at a timestamp. All others are values that exist in the script already.
So this is more along the lines of what I'm looking for.. Its what I have now, but doesn't work.
$sql = "INSERT INTO videos (id, title, timestamp, views, length, image, vid_url, cetegory, reciter, genre)
VALUES (:id, :title, :timestamp, :views, :length, :image, :vid_url, :category, :reciter, :genre)";
$query = $DBH->prepare($sql);
$results = $query->execute(array(
":id" => '',
":title" => $title,
":timestamp" => time(),
":views" => '0',
":length" => $length,
":image" => '',
":vid_url" => $name,
":category" => $cat,
":reciter" => $reciter,
":genre" => $genre
));
If id is an autoincrement, don't pass it to your query. If you specify a value to be inserted to an autoincrement table, sql will attempt to insert that value. so don't include it in the query, let SQL do that.
Secondly, if the third field is a timestamp, set the default to
CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
SQL will update the timestamp automatically on update or insert (if you only want it on insert just put CURRENT_TIMESTAMP. then you also can drop that row.
You can also drop the images row if you aren't inserting anything there either, no point to put something in the query if you're not using it!
Also, the key PDO looks for doesn't have the colon (:) so if your item is :title, the array key will be just 'title'. So, your code should look something like:
$sql = "INSERT INTO videos ( title, views, length,, vid_url, cetegory, reciter, genre)
VALUES (:title, :views, :length, :vid_url, :category, :reciter, :genre)";
$query = $DBH->prepare($sql);
$results = $query->execute(array(
"title" => $title,
"views" => '0',
"length" => $length,
"vid_url" => $name,
"category" => $cat,
"reciter" => $reciter,
"genre" => $genre
));

Filling date column with current date and time?

I have this code for adding new products to my database, but It does'nt work at all.
I want that date be inserted automaticly by code not manually, and because of that I used now() in my mysql, but now I use PDO and I have now idea, how could I do it. Here is my code:
<?php
require"../scripts/config.php";
if(isset($_POST['product_name'])){
$product_name = $_POST['product_name'];
$product_category= $_POST['product_category'];
$product_quality= $_POST['product_quality'];
$product_size = $_POST['product_size'];
$product_price = $_POST['product_price'];
$product_description= $_POST['product_description'];
$q = "INSERT INTO tuotteet (name, category, quality, size, price, description, date_add)
VALUES(:name, :category, :quality, :size, :price, :description, NOW())";
require "../scripts/connect.php";
$query = $connect->prepare($q);
$result = $query->execute(array(
":name" => $product_name,
":category" => $product_category,
":quality" => $product_quality,
":size" => $product_size,
":price" => $product_price,
":description" => $product_description
));
}
?>
You are using NOW() in SQL which is good approach, but you are also trying to pass in the :date_add parameter which doesn't exist in the SQL as a placeholder. Don't bind value on :date_add when you execute().
You need to check for and handle errors around your database accesses.
And you're also missing a single quote at if (isset($_post['product_name])) which should have been if (isset($_post['product_name']))

Improve sql query function performance

I'm new to PHP, and was wondering if anyone could give an example of how to improve this code?
public function createContent($title, $content, $category_id){
try {
$user_id = $_SESSION["user_id"];
if(!$user_id){
return(false);
}
$sql = "INSERT INTO content (title, content, user_id, category_id)
VALUES (:title, :content, :user_id, :category_id)";
$query = $this->_db->prepare($sql);
$execute_array = array(
':title' => $title,
':content' => $content,
':user_id' => $user_id,
':category_id' => $category_id
);
$query->execute($execute_array);
}
catch(PDOException $e){
echo $e->getMessage();
}
}
what do you mean with improve??
if your table only have "title, content, user_id, category" you can do it like:
"insert into content (:title, :content,:user_id, :category)";
but the best advice is to prepare statement, that will help you to avoid sql-injection

Categories