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
Related
I am trying to insert multiple rows into a table based on the array...with each $value being each of the comma separated values.
I know this is NOT the best way or even correct way to do this - just trying to get some guidance on how to achieve this the right way.
$someArray=array(96,97,98,99,100,101,103,105);
foreach($someArray as $value){
$sql = "INSERT INTO bid_package(user_company) VALUES('".$value."');";
echo $sql;
echo "<br />";
INSERT INTO bid_package(user_company) VALUES('96');
INSERT INTO bid_package(user_company) VALUES('97');
INSERT INTO bid_package(user_company) VALUES('98');
INSERT INTO bid_package(user_company) VALUES('99');
INSERT INTO bid_package(user_company) VALUES('100');
INSERT INTO bid_package(user_company) VALUES('101');
INSERT INTO bid_package(user_company) VALUES('103');
INSERT INTO bid_package(user_company) VALUES('105');
You can put multiple lists of values in a single INSERT:
$values = implode(', ', array_map(function($val) {
return "($val)";
}, $someArray));
$sql = "INSERT INTO bid_package (user_company) VALUES $values;";
This will create a query that looks like this:
INSERT INTO bid_package (user_company) VALUES (96), (97), (98), (99), (100), (101), (103), (105);
If you were using PDO, it would be better to use a prepared statement, to prevent SQL-injection.
$values = implode(', ', array_fill(0, count($someArray), "(?)"))
$sql = "INSERT INTO bid_package (user_company) VALUES $values;"
$stmt = $conn->prepare($sql);
$stmt->execute($someArray);
First, you should be using prepared statements instead of inserting the variable directly into the query. Here is one way of doing what you are attempting.
$mysqli = new mysqli('localhost', 'user', 'password', 'mysampledb'); // your mysqli handle
$stmt = $mysqli->prepare("INSERT INTO SampleTable VALUES (?)"); // prepare your query
//bind value as a reference
$stmt->bind_param('s', $val);
//define values
$someArray=array(96,97,98,99,100,101,103,105);
//loop through values
foreach($someArray as $val) {
//execute statement
$stmt->execute();
}
If you are ever passing data to a query, you should use prepared statements.
I need to insert to two tables and I tried transactions. It works well:
$nom = "Nrc";
$contrasenya = "somePassword";
$conn->beginTransaction();
$conn->exec("INSERT INTO usuari (nom, contrasenya)
VALUES ('$nom', '$contrasenya')");
$conn->exec("INSERT INTO well (puntuacio, text)
VALUES ('9', 'some text2')");
$conn->commit();
echo "New records created successfully";
Now I want to introduce prep. statements for security. I am not sure how to do that. This is what I tried. It gives me no error, but it does not insert in any table either:
$nom = "Nrc";
$contrasenya = "somePassword";
$conn->beginTransaction();
$stmt = $conn->prepare("INSERT INTO usuari (nom, contrasenya)
VALUES (:nom, :contrasenya)");
$stmt = $conn->prepare("INSERT INTO well (puntuacio, text)
VALUES ('9', 'some text2')");
$stmt->bindParam(':nom', $nom);
$stmt->bindParam(':contrasenya', $contrasenya);
$conn->commit();
echo "New records created successfully";
There are several issues with your code:
You never execute the statement.
You overwrite your statement ($stmt) with the statement using the values directly. So you don't use the correct prepared statement.
You can use the following code to INSERT the values to the tables:
//start the transaction.
$conn->beginTransaction();
//the variables of the first statement.
$nom = 'Nrc';
$contrasenya = 'somePassword';
//prepare the first statement, bind the values and execute.
$stmt = $conn->prepare("INSERT INTO usuari (nom, contrasenya) VALUES (:nom, :contrasenya)");
$stmt->bindParam(':nom', $nom);
$stmt->bindParam(':contrasenya', $contrasenya); //TODO - use hashing here!
//... or solution without variable.
//$stmt->bindValue(':nom', 'Nrc');
//$stmt->bindValue(':contrasenya', 'somePassword');
$stmt->execute();
//the variables of the second statement.
$puntuacio = '9';
$text = 'some text2';
//prepare the second statement, bind the values and execute.
$stmt = $conn->prepare("INSERT INTO well (puntuacio, text) VALUES (:puntuacio, :text)");
$stmt->bindParam(':puntuacio', $puntuacio);
$stmt->bindParam(':text', $text);
//... or solution without variable.
//$stmt->bindValue(':puntuacio', '9');
//$stmt->bindValue(':text', 'some text2');
$stmt->execute();
//commit all changes of the transaction.
$conn->commit();
Note: As already others mentioned, you should also hash your passwords.
From php.net:
Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.
For password insertion you should use password() function shiped with PHP.
You shouldn't insert direct data directly in prepare statement, as you did for the first one
$stmt = $conn->prepare("INSERT INTO well (puntuacio, text)
VALUES (:number, :some_text)");
$stmt->bindParam(':number', $num);
$stmt->bindParam(':some_text', $text);
You should execute(); your prepared statement in order to execute your query insertion.
Plus as said previously you overwrite your $stmt variable before you can execute your query.
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);
}
I have a form something like below:
<input name="first_name[]" type="text">
<input name="last_name[]" type="text">
<input name="email[]" type="email">
I am using while loop to print/echo number of groups of above form fields it required.
There will be multiple data in it, i'm not understanding how use insert query to insert data in mysql table using php.
First, you will need to know how many records you are trying to insert. I used first_name for this, but you could use any of them. (I am assuming since these are grouped together that you will always have the same number of first_name, last_name, and email.):
$count = count($_POST['first_name']);
After you know that, you can build an SQL statement that will insert all of the records in one query:
$sql = "INSERT INTO people (first_name, last_name, email) VALUES ";
$sql .= implode(', ', array_fill(0, $count, '(?, ?, ?)'));
The second line (implode...) will create sets of placeholders in the statement for each record you are trying to insert. (The three question marks represent the three columns you are inserting.) For example, if you had two field groups, the statement would look like:
INSERT INTO people (first_name, last_name, email) VALUES (?, ?, ?), (?, ?, ?)
After you have created the SQL string, you can create a new PDO connection and use that connection to create a prepared statement using your SQL.
$pdo = new PDO($dsn, $user, $password);
$statement = $pdo->prepare($sql);
Next you need to bind your values to the prepared statement. There are various different ways to do this. Here is one example:
// Create a multidimensional array using each of the fields from your field groups
$columns = array($_POST['first_name'], $_POST['last_name'], $_POST['email']);
$index = 1; // This is the index of the placeholder in the prepared statement
for ($i=0; $i < $count; $i++) { // This will loop as many times as you have field groups
$row = array_column($columns, $i);
// using array_column will pull everything from the $i index of each of the sub-arrays
// e.g. first_name[$i], last_name[$i], email[$i]
foreach ($row as $value) {
// bind the value and increment the index
$statement->bindValue($index, $value);
$index++;
}
}
After you have bound all the parameters, you can execute the prepared statement:
$statement->execute();
You can try something like this (you can find comments in the code):
if (isset($_POST['yourSubmitButton']) && isset($_POST['first_name'])) {
try {
$conn = new PDO("mysql:host=localhost;dbname=mysql", 'db_username', 'db_password');
}
catch(PDOException $e) {
echo $e->getMessage();
die();
}
$sql = 'INSERT INTO your_table (first_name, last_name, email) VALUES ';
$sql_append = array(); //Here we have the placeholder to be inserted
$binds = array(); //Here he have the values for the placeholders
for($i = 0; $i < count($_POST['first_name']); $i++) {
if (!( isset($_POST['first_name'][$i]) && isset($_POST['last_name'][$i]) && isset($_POST['email'][$i]) )) {
//We need all the values to be valid
continue;
}
//Add the placeholders and bind values
$sql_append[] = '(first_name = :first_name'.$i.', last_name = :last_name'.$i.', email = :email'.$i.')';
$binds[':first_name'.$i] = $_POST['first_name'][$i];
$binds[':last_name'.$i] = $_POST['last_name'][$i];
$binds[':email'.$i] = $_POST['email'][$i];
}
//Implode and add to the query and then execute
$sql = $sql.implode(', ', $sql_append).';';
$stmt = $conn->prepare($sql);
$stmt->execute($binds);
}
If you have 2 rows $sql will have:
echo $sql;
Result:
INSERT INTO your_table (first_name, last_name, email) VALUES (first_name = :first_name0, last_name = :last_name0, email = :email0), (first_name = :first_name1, last_name = :last_name1, email = :email1);
I'm wondering how to insert multiple values into a database.
Below is my idea, however nothing is being added to the database.
I return the variables above (email, serial, title) successfully. And i also connect to the database successfully.
The values just don't add to the database.
I get the values from an iOS device and send _POST them.
$email = $_POST['email'];
$serial = $_POST['serial'];
$title = $_POST['title'];
After i get the values by using the above code. I use echo to ensure they have values.
Now I try to add them to the database:
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = '$email'");
if (mysqli_num_rows($assessorEmail) == 0) {
echo " Its go time add it to the databse.";
//It is unqiue so add it to the database
mysqli_query($connection,"INSERT INTO assessorID (email_address, serial_code, title)
VALUES ('$email','$serial','$title')");
} else {
die(UnregisteredAssessor . ". Already Exists");
}
Any ideas ?
Since you're using mysqli, I'd instead do a prepared statement
if($stmt = mysqli_prepare($connection, "INSERT INTO assessorID (email_adress, serial_code, title) VALUES (?, ?, ?)"))
{
mysqli_stmt_bind_param($stmt, "sss", $email, $serial, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is of course using procedural style as you did above. This will ensure it's a safe entry you're making as well.