I would like to have a bit of clarification about prepared statements, and how they behave when assembled in other ways.
The sample code below is from Straight out this W3 entry. My problem is that, having many more values than the four provided in this example, I'd love to store them in an array and then run a foreach to prepare each string.
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
// insert another row
$firstname = "Mary";
etc
Would the edit below be safe for application, or does it crack the whole point of prepared statements?
$stuff = array("firstname", "lastname", "email");
foreach ($stuff as $singlestuff) {
$singlestuff1 = ':'.$singlestuff;
$singlestuff2 = '$'.$singlestuff;
$stmt = $conn->prepare("INSERT INTO MyGuests ($singlestuff1) ) VALUES ($singlestuff2)");
$stmt->bindParam($singlestuff1, $singlestuff2);
}
Sorry for any macroscopic mistake, the code is just an illustration of the concept.
Thanks in advance!
Bind within the foreach loop, assumed the variables exist:
foreach ($stuff as $singlestuff) {
$stmt->bindParam(':' . $singlestuff, $$singlestuff);
}
Related
I tried to insert multiple rows to PDO MySQL but it's didn't work
my code is below
<input type="text" name="firstname[]"> <input type="text" name="lastname[]">
function input_checker($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$firstname = input_checker($_POST["firstname"]);
$lastname = input_checker($_POST["lastname"]);
$rows = array($firstname, $lastname);
$stmt = $conn->prepare("INSERT INTO memo(ID, firstname, lastname)
VALUES (NULL, :firstname, :lastname)");
foreach($rows as $key => $value){
$stmt->bindParam($key, $value);
}
$stmt -> execute();
$rows is not an associative array, so there's no :firstname and :lastname keys in it. Also, bindParam() binds to references, so using the same $value variable each time through the loop will bind both parameters to the last value from the loop.
You don't need the array in the first place. Just bind each parameter separately.
But $_POST['firstname'] and $_POST['lastname'] are arrays, so you need to loop through them.
$firstname = $lastname = null;
$stmt = $conn->prepare("INSERT INTO memo(ID, firstname, lastname)
VALUES (NULL, :firstname, :lastname)");
$stmt->bindParam(":firstname", $firstname);
$stmt->bindParam(":lastname", $lastname);
foreach ($_POST['firstname'] as $i => $firstname) {
$lastname = $_POST['lastname'][$i];
$stmt->execute();
}
You are binding with the array index as the key (which are numeric in the version you are using), but you are using names for the parameters.
There is no need to use an array anyway as it is shorter to bind each parameter at a time...
$stmt = $conn->prepare("INSERT INTO memo(ID, firstname, lastname)
VALUES (NULL, :firstname, :lastname)");
$stmt->bindParam(":firstname", $firstname);
$stmt->bindParam(":lastname", $lastname);
$stmt -> execute();
I am trying to figure out how prepared statements work in PDO. I have the following file:
<?php
$user = "root";
$pass = "<removed for this post>";
$db = new PDO("mysql:host=localhost;dbname=pdo-demo", $user, $pass);
$stmt = $db->prepare("INSERT INTO pdo-demo (firstname, lastname, email) value (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
$firstname = "John";
$lastname = "Doe";
$email = "johndoe#nowhere123.com";
$stmt->execute();
$db = null;?>
When I enter the page nothing happens, what am I missing? Shouldn't it insert the data?
pdo-demo that translates to pdo minus demo And your using that name for database AND table.
Turns out I needed backticks (`) for the variable names like so:
$stmt = $db->prepare("INSERT INTO `pdo-demo` (`firstname`, `lastname`, `email`) value (:firstname, :lastname, :email)");
Now it worked
I am using the Nested Foreach loop to store the data in the mysql. But its taking too much processing time. How i can reduce the maximum execution time.
foreach ($results as $r) {
mysqli_query($con,"insert into commercial values('".mysqli_real_escape_string($con,$r['MST_MLS_NUMBER'])."')");
$val=1;
$objects = $rets->GetObject('Property', 'Photo', $r['MST_MLS_NUMBER'], '*', 0);
foreach ($objects as $pho) {
mysqli_query($con,"insert into cmtval values('".mysqli_real_escape_string($con,$r['MST_MLS_NUMBER'])."')");
}
}
You should use bulk insert
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
By foreach loop you should make first query to execute and then execute query with mysqli_query.
$query1 = "insert into commercial values ";
$query2 = "insert into cmtval values ";
foreach ($results as $r)
{
$query1 .= "('" . mysqli_real_escape_string( $con, $r['MST_MLS_NUMBER']) . "'), ";
$val=1;
$objects = $rets->GetObject('Property', 'Photo', $r['MST_MLS_NUMBER'], '*', 0);
foreach ($objects as $pho)
{
$query2 .= "('" . mysqli_real_escape_string( $con, $r['MST_MLS_NUMBER']) . "'), ";
}
}
mysqli_query($con, $query1);
mysqli_query($con, $query2);
I haven't tested code. Test and let me know if anything is missing.
Batch updates reduces some time.
Also if you are saving too much data in DB in single query and if you too much indexes it takes time to insert data.
you can make something like this
foreach ($results as $r)
{
mysqli_query($con,"insert into commercial values('".mysqli_real_escape_string($con,$r['MST_MLS_NUMBER'])."')");
$val=1;
$objects = $rets->GetObject('Property', 'Photo', $r['MST_MLS_NUMBER'], '*', 0);
// generate partial query strings for insert multiple records
$numbers=array();
foreach ($objects as $pho)
{
$numbers[]= "('".mysqli_real_escape_string($con,$pho['MST_MLS_NUMBER'])."')";
}
mysqli_query($con,"insert into cmtval values".implode(",",$numbers)); // it will insert multiple record
}
You can use a prepare statement and execute with different values to be inserted
For example
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie#example.com";
$stmt->execute();
Set parameters and execute line should be in your foreach loop.
Prepared Statements and Bound Parameters
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.
Prepared statements basically work like this:
Prepare: An SQL statement template is created and sent to the
database. Certain values are left unspecified, called parameters
(labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?) The
database parses, compiles, and performs query optimization on the SQL
statement template, and stores the result without executing it
Execute: At a later time, the application binds the values to the
parameters, and the database executes the statement. The application
may execute the statement as many times as it wants with different
values
I am having trouble inserting data into my database. This is my first time dealing with SQL injection.
$stmt = $dbConnection->prepare('INSERT INTO users(name) VALUES('name = ?')');
$stmt->bind_param('s', $name);
$stmt->execute();
But that doesn't work. Any help would be appriciated!
You have a few syntax errors in your code. Try this:
$stmt = $dbConnection->prepare('INSERT INTO users (name) VALUES (:s)');
$stmt->bindParam(':s', $name);
$stmt->execute();
If you want to insert and define more values, do it like this:
$stmt = $dbConnection->prepare('INSERT INTO users (name, email) VALUES (:s, :email)');
$stmt->bindParam(':s', $name);
$stmt->bindParam(':email', $email);
$stmt->execute();
If you're using mysqli, your code will look like this:
$stmt = $dbConnection->prepare('INSERT INTO users (name) VALUES (?)');
$stmt->bind_param('s', $name);
$stmt->execute();
You don't need name = in the SQL, the column name is specified in the list (name) after the table name. Just put a ? where you would normally put the value.
$stmt = $dbConnection->prepare('INSERT INTO users(name) VALUES(?)');
$stmt->bind_param('s', $name);
$stmt->execute();
I have been ripping my hair for days over this problem so any helpful advice would be appreciated. Calling the following function returns nothing. The POST values are set (They print with echo) and the database let me update and extract with other functions. What am i missing?
Oh yea, all the values are strings.
$stmt = $db->prepare("INSERT INTO content_page (name, layout, page_id) VALUES (?,?,?)");
$stmt->bind_param("sss", $_POST['name'], $_POST['layout'], $_POST['page_id']);
$stmt->execute();
$stmt->close();
At glance, there is nothing wrong with this code (in case you are indeed using mysqli). So, the only way to get to know what is going wrong is to get the error message.
Add this line before connect
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
and make sure you can see PHP errors
Try this
$sql = "INSERT INTO content_page (name, layout, page_id) VALUES (?,?,?)";
if (!$stmt = $db->prepare($sql)) {
die($db->error);
}
$stmt->bind_param("ssi", $_POST['name'], $_POST['layout'], $_POST['page_id']);
if (!$stmt->execute()) {
die($stmt->error);
}
$stmt->close();
Or, if, as you said, all your values are strings (given, they are as well defined as varchars/something similar in your database), you can still bind_param("sss"...
Aren't page_id's integers ? Since the asker first tagged the question as PDO, here is the PDO version :
$stmt = $db->prepare("INSERT INTO content_page (name, layout, page_id) VALUES (:name,:layout,:pid)");
$sth->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$sth->bindParam(':layout', $_POST['layout'], PDO::PARAM_STR);
$sth->bindParam(':pid', $_POST['page_id'], PDO::PARAM_INT);
$stmt->execute();
Or (MySQLi):
$stmt = $db->prepare("INSERT INTO content_page (name, layout, page_id) VALUES (?,?,?)");
$stmt->bind_param("ssi", $_POST['name'], $_POST['layout'], $_POST['page_id']);
$stmt->execute();
Or (PDO) :
$stmt = $db->prepare("INSERT INTO content_page (name, layout, page_id) VALUES (?,?,?)");
$stmt->execute(array($_POST['name'], $_POST['layout'], $_POST['page_id']));
Here you are:
$name = $_POST['layout'];
$layout = $_POST['layout'];
$page_id= $_POST['page_id'];
$stmt = $db->prepare("INSERT INTO content_page (name, layout, page_id) VALUES ('".$name."','".$layout."','".$page_id."')");