need help with this syntax it only stores the last value of my array into the database.
<?php
if(isset($_POST["submit"])) {
$lines=preg_split('/\r\n|[\r\n]/', $_POST['text']);
foreach($lines as $line => $value)
$quer = "INSERT INTO wew (wewe) VALUES('$value')";
if ($conn->query($quer) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $quer . "<br>" . $conn->error;
}
}
?>
You should add bracket to your foreach. Without that, only the next line will be in the loop.
so you should have:
foreach($lines as $line => $value) {
$quer = "INSERT INTO wew (wewe) VALUES('$value')";
if ($conn->query($quer) === TRUE) {
echo "New record created successfully";
}
}
I advice you to use bracket for all your conditions and loops since the readability is better and you avoid errors like that.
foreach($lines as $line => $value) { // Add braces near foreach
$quer = "INSERT INTO wew (wewe) VALUES('$value')";
if ($conn->query($quer) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $quer . "<br>" . $conn->error;
}
}// close foreach
Related
Is there any way to loop a session variable with an array value to insert into the database?
$list_application which where I store the array value
You will see in my code that I've directly insert the $list_application and it returns an Array when I printed it out.
if(isset($_POST['submit'])) {
include('includes/dbconn.php');
$list_application = $_SESSION['LIST_APPS'];
$currUser= getenv("username");
$get_data = "INSERT INTO technologyresults(examdate, technology, prof, eid) VALUES(CURDATE(),'$list_application', '$list_application','$currUser')";
if($conn->query($get_data) === TRUE ) {
include('includes/dbconn.php');
} else {
echo "Error: " . $get_data. "<br>" . $conn->error;
}
$conn->close();
header('location: summary.php');
}
if I understood your question correctly, then what yyou need is to implode the array to a string that would match the insert:
$list_application = implode("','", $_SESSION['LIST_APPS']) ;
and in you code, notice I changed the INSERT a bit:
if(isset($_POST['submit'])) { include('includes/dbconn.php');
$list_application = implode("','", $_SESSION['LIST_APPS']) ;
$currUser= getenv("username"); $get_data = "INSERT INTO technologyresults(examdate, technology, prof, eid) VALUES(CURDATE(),'".$list_application. "','$currUser')"; if($conn->query($get_data) === TRUE ) { include('includes/dbconn.php'); } else { echo "Error: " . $get_data. "<br>" . $conn->error; } $conn->close(); header('location: summary.php'); }
I have a loop that looks like this:
/* For Loop for all sheets */
for($i=0;$i<$totalSheet;$i++) {
$Reader->ChangeSheet($i);
foreach ($Reader as $Row) {
//variables here
$query = "INSERT INTO schools (
//code here
)";
if ($mysqli->query($query) === TRUE) {
echo "<br> New record created successfully <br>";
} else {
echo "Error: " . $query . "<br>" . $mysqli->error;
}
}
}
How do I turn this:
if ($mysqli->query($query) === TRUE) {
echo "<br> New record created successfully <br>";
into a code that will show something like:
XX inputted successfully
{list of schools with ID listed here}
XX not inpputed due to errors
{list of schools not inputted}
Would like to see a simple summary of the entire loop rather than seeing a repeated result of each loop that occurred.
Collect all the information you want in variables, and print them at the end.
$success = $fail = "";
$success_count = $fail_count = 0;
for($i=0;$i<$totalSheet;$i++) {
$Reader->ChangeSheet($i);
foreach ($Reader as $Row) {
//variables here
$query = "INSERT INTO schools (
//code here
)";
if ($mysqli->query($query)) {
$success .= "<li>" . $Row['school_name'] . "</li>";
$success_count++;
} else {
$fail .= "<li>" . $Row['school_name'] . "</li>";
$fail_count++;
}
}
}
echo $success_count . " inputted successfully:<br><ul>" . $success . "</ul>";
echo $fail_count . " not inputted due to errors:<br><ul>" . $fail . "</ul>";
Replace $Row['school_name'] with whatever the correct variable is for the school name in your data.
I get a text from html-form, didnt mention it here, but it looks like:
John:John
Mike:Mike
Root:Admin
Here is my php code:
$text = explode("\n", $_POST["info"]);
// - get data from html form and //explode it to pieces
print_r($text);
// result is: Array ( [0] => John:John [1] => Mike:Mike [2] => Root:Admin )
foreach ($text as $key => $value) {
$val = explode (":", $value);
// want to explode it to pieces, result must be 0=>John 1=>John, 0=>Mike 1=>Mike, [0]=>Root [1]=>Admin
$sql = "INSERT INTO `redtable`(`NAME`,`NAME2`) VALUES('$val[0]','$val[1]');";
}
When this code runs, it inserts into database only the last line, which are (Root:Admin), why it doesn't inserts John:John, Mike:Mike ...?
Where is the mistake?
Here is the result of echo $sql:
INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('John','John ');INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('Mike','Mike ');INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('Root','Admin');
Here is the full code:
<?php
$servername = "localhost";
$username = "mysql";
$password = "mysql";
$dbname = "red";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$pieces = explode("\n", $_POST["info"]);
foreach ($pieces as $key => $value) {
$val = explode (":", $value);
$sql = "INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('$val[0]','$val[1]');";
echo $sql;
}
if ($conn->query($sql) === TRUE) {
echo "Days left updated";
} else {
mysqli_error($conn);
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Have trying using if-else statements, like this:
# code...
$val = explode (":", $value);
# print_r($val);
if (1 == 1) {
$sql = "INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('$val[0]','$val[1]');";
}
else {
echo "esle";
}
}
The same result, only the last line have been inserted to the DB.
GUYS, If SOMEONE NEED THE WORKING SOLUTION WATCH #Matt Rabe answer - working like a charm, you need just replace the brackets!
Mark Baker is right - you are executing your sql outside of your foreach loop. You are defining the $sql var inside your foreach, but the actual execution of it ($conn->query($sql)) occurs outside of the foreach.
Change this:
foreach ($pieces as $key => $value) {
$val = explode (":", $value);
$sql = "INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('$val[0]','$val[1]');";
echo $sql;
}
if ($conn->query($sql) === TRUE) {
echo "Days left updated";
} else {
mysqli_error($conn);
echo "Error: " . $sql . "<br>" . $conn->error;
}
To this:
foreach ($pieces as $key => $value) {
$val = explode (":", $value);
$sql = "INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('$val[0]','$val[1]');";
echo $sql;
if ($conn->query($sql) === TRUE) {
echo "Days left updated";
} else {
mysqli_error($conn);
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Your code has numerous issues beyond this, but this should address your stated question.
I have been retrieving call logs from a cdr and dumping them into a database in MySQL. Of late the database crashes and the was giving me duplicates and junk characters so i modified to the below code.
modified code
$file1 = file_get_contents('file:///C:/Users/thy/Desktop/2011_0419_1531_v3.12R/cdr/'.$newname, FILE_USE_INCLUDE_PATH);
$arr1 = explode("\n", $file1);
foreach ($arr1 as $key => $value) {
$colArray = [];
$colArray['id'] = null;
$colArray['hashkey'] = md5(uniqid(rand(), true));
$split = explode(";", $value);
foreach ($split as $key => $val) {
# code...
$arr = (explode('=', $val));
$field = 'ch';
$item = '0';
$field = $arr[0];
$item = $arr[1];
$item = str_replace(str_split(')(\/'), '', $item);
$colArray[$field] = $item;
}
$columns = implode(', ', array_keys($colArray));
$values = implode(', ', $colArray);
$sql = "INSERT INTO `call`.`logs` (" . $columns . ") VALUES (" . $values . ")";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
the above code keeps giving me errors
Error: INSERT INTO call.logs (id, hashkey, ) VALUES (,
797d8782a433b30e196fafc0ce01d09b, )You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near ') VALUES (,
797d8782a433b30e196fafc0ce01d09b, )' at line 1
Original code is below (the one i modified it from)
$file1 = file_get_contents('file:///C:/Users/thy/Desktop/2011_0419_1531_v3.12R/cdr/'.$newname, FILE_USE_INCLUDE_PATH);
$arr1 = explode("\n", $file1);
$data1 = array();
foreach ($arr1 as $key => $value) {
$split = explode(";", $value);
$keys = md5(uniqid(rand(), true));
//insert key to identify call.
$sql = "INSERT INTO `call`.`logs` (`id`, `hashkey`) VALUES (NULL, '{$keys}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
foreach ($split as $key => $val) {
# code...
$arr=(explode('=', $val));
$field='ch';
$item='0';
$field=$arr[0];
$item=$arr[1];
echo $field . " --";
echo "<br/>";
echo $item;
//sql
$sql = "UPDATE logs SET {$field}='{$item}' WHERE hashkey='{$keys}'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
echo "done";
//$conn->close();
} echo "<br/>";
}
?>
<?php
I think the problem is with the generated/devised INSERt statement
INSERT INTO call.logs (" . $columns . ") VALUES (" . $values . ")";
There is an extra comma getting appended without column name?
If id is an autoincremental field. Try this:
INSERT INTO call.logs (id, hashkey) VALUES (default, '797d8782a433b30e196fafc0ce01d09b')
Below I have Php code that loops through an array and for each it checks if the value already exists in the database and if not, create it. The code itself is working but the loop itself can be insanely big, maximum of a couple tens thousand iterations.
How can I optimize this code? What to use and how to use. There should be a better way to insert this many times without looping through each individual.
foreach($arr as $value){
$checkID = mysqli_query($cenn, "SELECT item_id from items WHERE item_id = '$value'");
if (!$checkID) {
die("Query '$checkID' failed to execute for some reason");
}else{
if (mysqli_num_rows($checkID) > 0) {
$user = mysqli_fetch_array($checkID);
echo "item_id" . checkID . "exists already";
}
else{
echo "item_id: '$user_id' doesn't exist<br>";
$gw2Api = file_get_contents("https://api.guildwars2.com/v2/items/" . $user_id); //12452 30704
$gw2Api_result = json_decode($gw2Api,true);
/*Here would be some code to determine values that are being inserted*/
if (!array_key_exists("description",$gw2Api_result)) {
$description = 'No description available...';
} else{
if($gw2Api_result['description'] === ''){
$description = "No description available...";
} else {
$description = $gw2Api_result['description'];
}
}
$insertItem = "INSERT INTO items
(item_id, name, description,
AccountBindOnUse, AccountBound,
last_update
)
VALUES ('$user_id', '$gw2Api_result[name]', '$description',
'$AccountBindOnUse', '$AccountBound', CURRENT_TIMESTAMP)";
if ($cenn->query($insertItem) === true) {
echo "New record '$user_id' created successfully";
} else {
echo "Error: " . $sql . "<br>" . $cenn->error;
}
}
}
} // end foreach
The question: How to insert many values, new rows, into mysqli database as fast as possible.
Just use bulk insert.
Collect all the rows for insertion and pass it in one query.
echo 'hi';
if (!empty($arr)) {
echo 'ok';
$values = "'" . implode("', '", $arr) . "'";
$qExistingItemIds = mysqli_query($cenn, "SELECT item_id from items WHERE item_id IN($values)");
$existingItemIds = [];
while ($existingItemId = mysqli_fetch_array($qExistingItemIds)) {
$existingItemIds[] = $existingItemId['item_id'];
}
$arr = array_diff($arr, $existingItemIds);
$inserts = array();
$i = 0;
$ic = count($arr);
foreach ($arr as $value) {
$i++;
echo "item_id: $value doesn't exist<br>";
$gw2Api = file_get_contents("https://api.guildwars2.com/v2/items/" . $value); //12452 30704
$gw2Api_result = json_decode($gw2Api,true);
/*Here would be some code to determine values that are being inserted*/
if (!array_key_exists("description", $gw2Api_result)) {
$description = 'No description available...';
} else {
if ($gw2Api_result['description'] === '') {
$description = "No description available...";
} else {
$description = $gw2Api_result['description'];
}
}
$inserts[] = "
('$value', '$gw2Api_result[name]', '$description', '$AccountBindOnUse', '$AccountBound', CURRENT_TIMESTAMP)
";
if ($i == 50 OR $i == $ic) {
$inserts = implode(",", $inserts);
$insert = "
INSERT INTO items
(item_id, name, description, AccountBindOnUse, AccountBound, last_update)
VALUES
$inserts
";
if ($cenn->query($insert) === true) {
echo 'great';
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $cenn->error;
}
$ic -= 50;
$i = 0;
$inserts = array();
}
}
}
so now we have only 2 queries. not thousands
details about bulk insert:
http://www.geeksengine.com/database/data-manipulation/bulk-insert.php
If you use prepared statement you should reduce the round trips to the database server and only compile and optimise each query once instead of Number_of_inputs * 2 queries. This should reduce the workload.
I would be very interested to know by how much.
$sql = "SELECT item_id from items WHERE item_id = ?";
$db_select = $cenn->prepare($sql);
if ( ! $db_select ) {
echo $cenn->error;
exit;
}
$sql_insert = "INSERT INTO items
(item_id, name, description,
AccountBindOnUse, AccountBound, last_update)
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)";
$db_insert = $cenn->prepare($sql);
if ( ! $db_insert ) {
echo $cenn->error;
exit;
}
foreach($arr as $value){
$db_select->bind_param('i', $value);
$res = $db_select->execute()
if ( $res === FALSE ) {
echo $cenn->error;
exit;
}
if ($db_select->num_rows > 0) {
// dont bother fetching data we already know all we need to
$user = $db_select->free();
echo "item_id $value exists already";
} else {
echo "item_id: $value doesn't exist<br>";
$gw2Api = file_get_contents("https://api.guildwars2.com/v2/items/" . $value);
$gw2Api_result = json_decode($gw2Api,true);
if ( ! array_key_exists("description",$gw2Api_result)
|| $gw2Api_result['description'] === '') {
$description = 'No description available...';
} else{
$description = $gw2Api_result['description'];
}
$db_insert->bind_param('issss', $value, $gw2Api_result[name],
$description, $AccountBindOnUse,
$AccountBound)
if ($cenn->query($insertItem) === true) {
echo "New record $value' created successfully";
} else {
echo "Error: " . $sql_insert . "<br>" . $cenn->error;
}
}
} // end foreach