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']))
Related
I have a numeric PHP variable named $quantity and based on the number set in this variable, I want to insert the same record in the MySQL table.
Example:
$quantity = '4';
$sql1 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
$sql2 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
$sql3 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
$sql4 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
You can achieve this by using a loop and a prepared statement. You need to execute the same statement multiple times. This is also very useful if the values are dynamic and they could change, e.g. the values are coming from user input.
Prerequisite:
You need to open a connection to your database. If you use MySQL then the connection would look something like this:
$pdo = new PDO("mysql:host=localhost;dbname=db_name;charset=utf8mb4", 'username', 'password', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
Now you can prepare a statement which we will execute in a loop multiple times.
$stmt = $pdo->prepare("INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());");
You can use any loop you like but for a simple scenario where we want the same code to be executed a number of times, a while loop is sufficient.
$quantity = 4;
while ($quantity--) {
$stmt->execute();
}
If it is easier for you, you can use for loop, too.
for($quantity = 0; $quantity < 4; $quantity++) {
$stmt->execute();
}
Try something like this:
// NOTICE - Make sure you are escaping any end-user supplied values correctly - See PHP docs for examples of how
$sql_template = 'INSERT INTO `table_quantity` (`username`, `code`, `quantity`, `data`) VALUES (\'John\', \'34438\', \'1\', now());';
$quantity = 5;
$sql = '';
foreach (range(1, $quantity) as $i) {
$sql .= $sql_template;
}
echo $sql;
See the following docs for explanations:
foreach
range()
append to string
Escape SQL values with PDO
Escape SQL values with MySQLi
I'm trying to insert the current date into a database for each entry within an array. I've found documentation for inserting the current date, but nothing that explains how to do it within an array.
<?php
$connect = new PDO("mysql:host=localhost;dbname=testing",
"root", "");
$query = "
INSERT INTO tbl_test
(full_name, id_number, email, pin_rank, team_name)
VALUES (:full_name, :id_number, :email, :pin_rank, :team_name)
";
for($count = 0; $count<count($_POST['hidden_full_name']); $count++)
{
$data = array(
':full_name' => $_POST['hidden_full_name'][$count],
':id_number' => $_POST['hidden_id_number'][$count],
':email' => $_POST['hidden_email'][$count],
':pin_rank' => $_POST['hidden_pin_rank'][$count],
':team_name' => $_POST['hidden_team_name']
);
$statement = $connect->prepare($query);
$statement->execute($data);
}
?>
I would like the current date to display in the last column within the table. Any help would be appreciated.
Assuming you've some kind of date column (date, datetime, etc...) and it's named in my example date_time, just do the following:
$query = "
INSERT INTO tbl_test
(full_name, id_number, email, pin_rank, team_name, date_time)
VALUES (:full_name, :id_number, :email, :pin_rank, :team_name, NOW())
"
Note, if you've got anything other than a date field, you'll get the time along this as well.
I'm not a big fan of the DB NOW because the DB uses it's own timezone settings separate from PHP.
So you can change the TimeZone in PHP and not in MySql and wind up with dates that are wrong (found that out the hard way one time).
And as that has been shown already, I'll show you how to do it with just PHP.
$query = "
INSERT INTO tbl_test
(full_name, id_number, email, pin_rank, team_name, created)
VALUES (:full_name, :id_number, :email, :pin_rank, :team_name, :created)
";
$today = (new DateTime)->format('Y-m-d H:i:s');
#$today = date('Y-m-d H:i:s'); //procedural
for($count = 0; $count<count($_POST['hidden_full_name']); $count++)
{
$data = array(
':full_name' => $_POST['hidden_full_name'][$count],
':id_number' => $_POST['hidden_id_number'][$count],
':email' => $_POST['hidden_email'][$count],
':pin_rank' => $_POST['hidden_pin_rank'][$count],
':team_name' => $_POST['hidden_team_name'],
':created' => $today
);
$statement = $connect->prepare($query);
$statement->execute($data);
}
You can of course get the date and time, within the loop if you need second precision but it's less efficient, due to multiple calls to DateTime.
I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:
$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);
So the query above will get the information from the database using $_GET[id] as a reference.
After this is performed, I want to insert the information retrieved in a different table using this code:
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();
if($count > 0) {
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help
You're not executing the query:
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
$results_insert = mysqli_query($cnx, $insert);
basically.
Plus...
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.
http://php.net/manual/en/mysqli.error.php
Sidenote:
Use mysqli_affected_rows() to check if the INSERT was truly successful.
http://php.net/manual/en/mysqli.affected-rows.php
Here's an example of your query in PDO if you'req planning to use PDO in future.
$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();
That's how we are more safe.
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
));
$q = "INSERT INTO accounts (from_bank, from_user, to_user, amount, date_time, notes) VALUES (:from_bank, :from_user, :to_user, :amount, :date_time, :notes)";
$query = $db->prepare($q);
$result = $query->execute(array(
":from_bank" => $from_bank,
":from_user" => $from_user,
":to_user" => $to_user,
":amount" => $amount,
":date_time" => $date_time,
":notes" => $notes
));
Ok this has been solved (cant answer my own question until level 8 currently im level 6) it was an unrelated line to do with $date_time = 'now()'; it was originally missing single quotes and now it works as it should I cant believe it didnt have any errors even tho I tryed using a try to catch any errors any ideas why this error wasnt caught?
in pdo you don't put single quotes around your parameters:
$q = "INSERT INTO accounts (from_bank, from_user, to_user, amount, date_time, notes) VALUES (:from_bank, :from_user, :to_user, :amount, :date_time, :notes)";
also here's a link to a tutorial you might find very useful:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers