Is it possible to insert multiple data with delay kind of thing/sleep for a few second?
for example here, Im going to insert the values (1,2) into my user table. Then after 5 seconds, it will proceed to insert value (3,4) into the same table, wait for 5 seconds and finally insert (5,6) into the table.
INSERT INTO User (col1, col2)
VALUES (1, 2), (3, 4), (5, 6)
Any suggestions are really appreciated!
<?php // da
$array = array(1, 2, 3, 4);
foreach ($array as $data) {
mysqli_query($conn,"INSERT INTO ... SET data='".$data."'");
sleep(1)
}
?>
Something like that? I did not understand very well.
I found the solution. Maybe it's a bit messy but this is what I've come with and solved my problem. Basically I just need to use prepare if I want to reuse the statement.
$stmt = $dbh->prepare("INSERT INTO user (col1, col2) VALUES ('1','2');
$stmt2 = $dbh->prepare("INSERT INTO user (col1, col2) VALUES ('3','4');
$stmt3 = $dbh->prepare("INSERT INTO user (col1, col2) VALUES ('5','6');
{ $stmt->execute();
sleep(5);
$stmt2->execute();
sleep(5);
$stmt3->execute();
}
That's all. Thanks for those who tried to solve this.
So what I do is create the query by concatenating it like this. But if you want to have multiple inserts you can call that function in a loop and remove this sleep put it in the loop outside the function or you can leave it there if the call is not a thread.
<?php
static function insert_table_db($anArra){
$dbconn = mysqli_connect(DB_HOST, DB_USER,DB_PASSWORD, DB_DATABASE) or die('MySQL connection failed!' . mysqli_connect_error());
mysqli_set_charset($dbconn, "utf8");
$query = "INSERT INTO `table`(`col1`, `col2`, `col3`, `col4`, `col5`) VALUES ";
$i = 1;
foreach ($anArray as $item) {
$query = $query . "(" . $item[0]. "," . $item[1]. "," . $item[2] . "," . $item[3] . ",'" . $item[4] . "')";
if (count($anArray) == $i){
$query = $query . ";";
} else {
$query = $query . ",";
}
$i++;
}
// Run query
if($dbconn->query($query) === true) {
$dbconn->close();
} else {
echo "Database Error: " . $dbconn->error;
$dbconn->close();
}
sleep(5);
}
?>
UPDATE: Sorry if some variables don't make sense I stripped it out of a library I have built and there are some extra things that I didn't delete ;D.
Related
I'm making an Android app that connects to a database online and lets the user edit the database from the application, I'm new to PHP and MySql but from my research I think I should be using an UPDATE statement, I've written the code below to register new users on the site from a tutorial, but I'd like to change the INSERT statement to an UPDATE statement so that instead of registering a new user, the App updates existing data that I have entered in PHPMYADMIN, could someone show me how to do this? Also, if you require the code for the app mention it in the comments and I'll add it to the question, I don't want to post too much unneccessary code. Thanks in advance.
<?php
require "conn.php";
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
$mysql_qry = "insert into patients(patient_name, check_in_date, room_number, bed_number, notes) values ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";
if($conn->query($mysql_qry) === TRUE) {
echo "Insert successful";
}
else{
echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
?>
EDIT
The fixed code is below, it now updates records already in the database rather than adding new data.
<?php
require "conn.php";
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
$mysql_qry = "UPDATE patients SET notes='$notes' WHERE patient_name='$patient_name'";
if($conn->query($mysql_qry) === TRUE) {
echo "Insert successful";
}
else{
echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
?>
first of all this PHP code is vulnerable to sql injection you should, no need to update your code to use either mysqli prepared statement or PDO prepared statement
secondly the easiest way I know you accomplish your goal would make a unique constraint on some columns and then use a mysql feature ON DUPLICATE UPDATE
for this example I'll assume that the unique fields determining an update instead of an insert are patient_name, check_in_date, room_number, and bed_number (in case john smith was in the same room as john smith in seprate beds) the query to update the table would be like this
ALTER TABLE `patients` ADD UNIQUE `unique_index`(`patient_name`, `check_in_date`, `room_number`, `bed_number`);
so now to address the sql injection bit and the query, I'll update the example to use mysqli statement and will assume patient_name and notes are strings (varchar/nvarchar), room_number and bed_number are integers, and check_in_date is a date
Edit My original answer had a syntax error in the query and also passing variables to the prepared statement below is the updated answer
$mysqliConn = new mysqli("localhost", "my_user", "my_password", "mydatabase");
$stmt = $mysqliConn->prepare("insert into patients
(patient_name, check_in_date, room_number, bed_number, notes)
values (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE notes=values(notes)");
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
mysqli_stmt_bind_param($stmt, "sdiis",
$patient_name, $check_in_date, $room_number, $bed_number, $notes);
hope this helps
Edit
Regarding the unique key, a unique key means that all fields in the unique key have to be unique when combined so for the example above
if record 1 is
patient_name, check_in_date, room_number, bed_number, notes
'john smith', '3/1/2017' , 413 , 2 , 'patient is sick'
and record two is
'jane doe' , '3/1/2017' , 413 , 2 , 'patient has wound'
these two records will note be duplicates with the above constraint but if you do need to change the constraint you can do the following
DROP the Constraint
ALTER TABLE `patients` DROP INDEX `unique_index`;
Then recreate the constraint like this
ALTER TABLE `patients` ADD UNIQUE `unique_index`(`patient_name`, `check_in_date`, `room_number`);
also if you named your constraint something other than unique_index you can find the key_name by running the following
SHOW INDEX FROM `patients`;
the name will be in the key_name column
additionally you may want to alter the last line of the query to be this in your php if you change the unique constraint so you can change bed number
ON DUPLICATE KEY UPDATE bed_number=values(bed_number), notes=values(notes)
You can also use REPLACE INTO, then you don't have to change the SQL statement. Let MySQL do the work for you.
https://dev.mysql.com/doc/refman/5.7/en/replace.html
<?php
require "conn.php";
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
$mysql_qry = "REPLACE INTO patients(patient_name, check_in_date, room_number, bed_number, notes) VALUES ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";
if($conn->query($mysql_qry) === TRUE) {
echo "Insert successful";
}
else{
echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
Also, you should really take a look at using PDO with prepared statements and parameters.
https://secure.php.net/manual/en/pdo.prepare.php
Actually I was looking for a small function that converts an INSERT MySQL query to an UPDATE query. So maybe other people were looking for the same and I think this is what the original poster was looking for aswell... I couldnt find any so I made this simple function which works for my needs, ofcourse you will have to make sure your original query is safe from MySQL injection.
It will convert
INSERT INTO aaa (bbb, ccc) VALUES ('111', '222')
to
UPDATE aaa SET ccc='222' WHERE bbb='111'
Use the 2nd variable ($iColumn) to identify the WHERE statement.
function convertInsertToUpdate($sQuery, $iColumn = 1) {
$sNewQuery = "";
$iPos = strpos($sQuery, ' (');
$sTmpTable = substr($sQuery, 0, $iPos);
$iPos = strpos($sTmpTable, 'INSERT INTO ');
$sTmpTable = substr($sTmpTable, $iPos+12);
$iPos = strpos($sQuery, ') VALUES (');
$sTmpValues = substr($sQuery, $iPos+10);
$iPos = strrpos($sTmpValues, ')');
$sTmpValues = substr($sTmpValues, 0, $iPos);
$iPos = strpos($sQuery, '(');
$sTmpColumns = substr($sQuery, $iPos+1);
$iPos = strpos($sTmpColumns, ') VALUES (');
$sTmpColumns = substr($sTmpColumns, 0, $iPos);
$aColumns = explode(', ', $sTmpColumns);
$aValues = explode(', ', $sTmpValues);
if (count($aColumns)>0 && count($aColumns) == count($aValues) && $iColumn < (count($aValues)+1)) {
$sNewQuery = "UPDATE ".$sTmpTable." SET";
$sTmpWhere = "";
$bNotFirst = false;
$iX = 0;
while ($iX<count($aColumns)) {
if ($iColumn == ($iX+1)) {
$sTmpWhere = " WHERE ". $aColumns[$iX]."=".$aValues[$iX];
$iX++;
continue;
}
if ($bNotFirst) {
$sNewQuery .= ",";
}
$sNewQuery .= " ".$aColumns[$iX]."=".$aValues[$iX];
$bNotFirst = true;
$iX++;
}
$sNewQuery .= $sTmpWhere;
}
return $sNewQuery;
}
$allgames = file_get_contents("https://steamspy.com/api.php?request=all");
$decodeall = json_decode($allgames, true);
foreach($decodeall as $game) {
$sql = "INSERT INTO games (name)
VALUES ('{$game['name']}')";
}
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
When i do this only the first row will be added. How do i insert multiple rows?
Just get rid of that multi query thing. Use a prepared statement instead
$stmt = $conn->prepare("INSERT INTO games (name) VALUES (?)");
$stmt->bind_param("s", $name);
foreach($decodeall as $game) {
$name = $game['name'];
$stmt->execute();
}
echo "New records created successfully";
Note that your current code with multi_query won't work as intended anyway, even with that silly typo fixed. You will have the result of only first query, having no idea what happened to all others.
You are overwriting the query each time. Try setting sql to blank then appending it each time in the loop.
Try this:
$sql = array();
foreach($decodeall as $game) {
$sql[] = "INSERT INTO games (name) VALUES ('{$game['name']}')";
}
$sqlInserts = implode(';', $sql);
if ($conn->multi_query($sqlInserts) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You don't need to perform the query multiple times like that, you can do it all in a single query without multi_query(). You can perform many INSERTs with a single query, like this
// Initialize the query-variable
$sql = "INSERT INTO games (name) VALUES";
// Loop through results and add to the query
foreach ($decodeall as $game) {
$sql .= " ('".$game['name']."'),";
}
// Remove the last comma with rtrim
$sql = rtrim($sql, ',');
// Perform the query
if ($conn->query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This will generate a query resembling
INSERT INTO games (name) VALUES ('One'), ('two'), ('Three')
which will insert the values One, Two and Three into separate rows.
This query will break if your $game['name'] variables contain an apostrophy ', so at the very least you should use $mysqli::real_escape_string(), although a prepared statement takes care of that and prevents SQL injection (so I recommend you go for that instead). See How can I prevent SQL injection in PHP?
Using a prepared statement - the better solution
The preferred method of executing a query is by using a prepared statement.
Fetch all the columns using array_column() and loop the array while calling the execute method until finished.
$stmt = $conn->prepare("INSERT INTO games (name) VALUES (?)");
$stmt->bind_param("s", $name);
foreach (array_column($decode, "name") as $name) {
$stmt->execute();
}
I have my table setup as shown in the image below.
When I try and run the following code to insert the values into the database I get the error:
FAIL: INSERT INTO Betfairodds
(Horse,Back,Lay,TimeformTR)VALUES( 'Intrepid','5.5', '5.9',
'0')
Would anyone be able to help, as I have tried to debug the code.
//loop through each individual card
foreach ($getdropdown2 as $dropresults) {
$horse = preg_replace('/\h*[^ a-zA-Z].*$/m', '', trim($dropresults->childNodes->item(8)->textContent));
$back = trim(GetBetween($dropresults->childNodes->item(18)->textContent, 'Back', '£'));
$lay = trim(GetBetween($dropresults->childNodes->item(20)->textContent, 'Lay', '£'));
$sql = "INSERT INTO `Betfairodds` (`Horse`,`Back`,`Lay`,`TimeformTR`)VALUES( '$horse','$back', '$lay', '0')";
$res = mysqli_query($db, $sql);
if (!$res) {
echo PHP_EOL . "FAIL: $sql";
trigger_error(mysqli_error($db), E_USER_ERROR);
}
}
I removed the quotes ' from 0 because it is defined as int in the schema and of-course added space right before VALUES ..try this:
$sql = "INSERT INTO `Betfairodds` (`Horse`,`Back`,`Lay`,`TimeformTR`) VALUES( '$horse','$back', '$lay', 0)";
Your statement is wrong. You should not put single quotes on the data fields. so it should be like:
$sql = "INSERT INTO `Betfairodds` (Horse,Back,Lay,TimeformTR)VALUES( '$horse','$back', '$lay', '0')";
I have a text file to read which has around 10000 points separated by,
x1,y1
x2,y2
x3,y3
.
.
10000 times
I read them using a loop in PHP and then store in an array and then I run a loop and insert one line at a time in my database. It takes really long time. Is there any way I can insert the whole array
for ($i=0; $i<10000; $i++)
{
$sql = '
INSERT INTO `firefly`.`FreeFormPoly`
(`markedObjectID`, `order`, `x`, `y`)
VALUES
('.$markedObjectsID.', '.$order.', '.$valuesx[i].','.$valuesy[i].')';
$db->query($sql, $markedObjectsID, $order, $values[1], $values[0]);
}
Try using multiple insert statement. Generate one insert and submit the entire statement
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
SO:
$sql = 'INSERT INTO `firefly`.`FreeFormPoly` (`markedObjectID`, `order`, `x`, `y`) VALUES';
for($i=0;$i<10000;$i++) {
if($i != 0) $sql .= ',';
$sql .= '('.$markedObjectsID.', '.$order.', '.$valuesx[i].','.$valuesy[i].')';
}
$db->query($sql);
I would do something like this:
$sql = 'INSERT INTO `firefly`.`FreeFormPoly` (`markedObjectID`, `order`, `x`, `y`) VALUES';
for($i=0;$i<length;$i++) {
$sql .= '('.$markedObjectsID.', '.$order.', .$valuesx[i].','.$valuesy[i].'),';
}
$sql = substr($sql,0,-1);
$db->query($sql);
Explanation:
The syntax to enter multiple records is
INSERT INTO TABLE_NAME VALUES(VAL1, VAL2, ....), (...), (...);
In the SQL you are concatenating (val1,val2,val3), every time you execute the loop hece you will get an extra , in the last position and substr() trims it off.
More preferably I would do
$sql = 'INSERT INTO `firefly`.`FreeFormPoly` (`markedObjectID`, `order`, `x`, `y`) VALUES ';
for($i=0;$i<length;$i++) {
$sql .= '('.$markedObjectsID.', '.$order.', .$valuesx[i].','.$valuesy[i].'),';
}
$sql = substr($sql,0,-1);
$result = mysqli_query($db,$sql)
or die('Error in querying the database');
You should be able to speed it up considerably by sending BEGIN TRANSACTION before the loop and COMMIT after the loop. One time I had to insert 14,000 data points on SQLite, and it took 20 minutes, but when I put the data in as a transaction it completed in 0.3 seconds.
First off, you can use prepared statements to reduce the network overhead. Assuming PDO:
$stmt = $db->prepare('INSERT INTO mytable (foo, bar, baz) VALUES (:foo, :bar, :baz)');
for ($i = 0; $i < $length; ++$i) {
$stmt->execute(array(
':foo' => $data[$i]['foo'],
':bar' => $data[$i]['bar'],
':baz' => $data[$i]['baz'],
));
}
Second, you could wrap the whole code inside $db->beginTransaction() and $db->commit().
I'm trying to load data from a few hundred text files into a database.
I believe MYSQL is exiting out of the loop without inserting all the rows.
Can anyone suggest how to insert blocks of 1000 rows to the end of data, with PHP code?
$filenames_array = array();
foreach($filenames_array as $filename)
{
$file_array = file($filename);
$file_value = $file_array[0];
$new_array = explode(",", $file_value);
$length = count($new_array);
for($i = 0; $i < $length; $i++)
{
$sql = "INSERT INTO `names`
(`id`, `name`)
VALUES
('',
'" . $new_array[$i] . "'
)";
$result = mysql_query($sql) or die(mysql_error());
echo $i . 'Row Inserted<br />';
}
}
you're probably trying to run too many INSERT statements in a single query.
look into PDO and prepared statements or use SQL syntax like this:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
Is it possible that one of the entries you're trying to insert contains a single quote '? In this case, an error would occur and the the loop wouldn't finish.
You should always escape the values you insert into the database with mysql_real_escape_string to prevent problems like that, and to make sure you're not vulnerable to sql injection.
$sql = "INSERT INTO `names`
(`id`, `name`)
VALUES
('',
'" . mysql_real_escape_string($new_array[$i]) . "'
)";
Why not combine every txt file into one big text file, and read it line by line? See the examples here http://php.net/manual/en/function.fgets.php
Mainly:
<?php
$handle = #fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>