Insert PHP Arrays as MYSQL columns - php

I am trying to add dynamic array values from two arrays into mysql table as columns, several rows at a time. I have created a loop for that.
When I run it it produces an error, stating that I have an error in MYSQL syntax. When I try to run the query statement that is produced directly in phpMyAdmin it runs fine. So the syntax shouldn't be an issue. Thanks for any help.
function addSystemDataTanks ($db, $tankNamesArray, $tankVolumesArray)
{
global $tankNamesArray;
global $tankVolumesArray;
global $noOfTanks;
$statement = "replace into tanks (TANK_NAME, TANK_VOLUME) ";
$statement .= "values ";
for ($i = 0; $i < $noOfTanks; $i++) {
$statement.= "('".$tankNamesArray[$i]."', '".$tankVolumesArray[$i]."'), ";
}
$statement.= rtrim($statement, ',');
$result = mysqli_query($db, $statement);
if ($result)
{
return true;
}else{
$errno = mysqli_errno($db);
echo "{h4}MySQL Error No: ".mysqli_errno($db)."</h4>";
echo "{h4}MySQL Error: ".mysqli_error($db)."</h4>";
echo "{h4}SQL: ".$statement."</h4>";
echo "{h4}MySQL Affected Rows: ".mysqli_affected_rows($db)."</h4>";
}
return 'NotAdded';
}

I see two problems so far:
First: where are you assigning a value to $noOfTanks ? your for loop depends on that value, however, i don't see it being assigned which means it is currently resulting in NULL, thus your loop not iterating.
Second: This line $statement .= rtrim($statement, ','); is concatenating to the original $statement variable thus ending up with this:
'REPLACE INTO tanks (TANK_NAME, TANK_VOLUME) values REPLACE INTO tanks (TANK_NAME, TANK_VOLUME) values '
I'm assuming you want to re-assign after your trim, in that case do this:
$statement = rtrim($statement, ',');

Related

Does php script slow down when echoing mysql queries to screen during loop

If I have a loop that inserts data into a mysql table, does me echoing the query to the screen slow down the script enough to make a significant difference?
for ($a=1;$a<=10000;$a++){
$ins = "INSERT into (number) values (".$a.")";
$stmt = $db->query($ins);
echo $ins."\n";
}
Actually for your case echoing is not very much time consuming but inserting a single column value with iteration e.g 10K times is somewhat time consuming and for your case your inserting 10K rows for one column inside loop. You can insert multiple row with a single query like this way-
INSERT INTO number(a) VALUES (4),(6),(7);
With MYSQL, You can include multiple lists of column values, each enclosed
within parentheses and separated by commas
More specifically, something like this-
$numbers = [];
for ($a=1;$a<=10000;$a++){
$numbers[] = '('.$a.')';
}
$b = implode(",", $numbers);
$ins = "INSERT into (number) values $b";
$stmt = $db->query($ins);
echo $ins."\n";
INSERT 10000 rows in 10000 iteration will take time not echo the query, actually.
I suggest you to store values into an array like:
<?php
$yourArray = array();
for ($a=1;$a<=10000;$a++){
$yourArray[] = $a;
}
?>
Then, outside the loop use implode() for comma seperated values
<?php
$yourQuery = "INSERT into (number) values ";
$yourQuery .= "("; // for starting bracket
$yourQuery .= implode("),(",$yourArray);
$yourQuery .= ")"; // for ending bracket
?>

Load data from JSON file to MYSQL database

I am trying to store two fields from the JSON data found here in a mysql database. First I create PHP arrays for the data I want using:
$o = file_get_contents("vixData.json");
$o = json_decode($o);
$date = [];
$close = [];
$set = $o->dataset->data;
foreach($set as $pos)
{
array_push($date,$pos[0]);
array_push($close,$pos[4]);
}
Works fine. Now I am trying to adapt This question on inserting multiple rows via a php array. First I implode my arrays:
$date = implode(",", $date);
$close = implode(",", $close);
Then try to insert to the db using:
$sql = "INSERT INTO vix (date,close) VALUES (".$date.",".$close.")";
if (mysqli_multi_query($dbc, $sql)) {
echo "VIX Load Successful";
} else {
echo "VIX Load Error";
}
I'm seeing my load error. There is no database connection issue because $dbc is used earlier in my script. Trying to debug; is my SQL INSERT statement valid? Can anyone see the issue?
Kind regards,
Just looking at it quickly, it seems your values are not wrapped in quotes in your SQL. Try this:
$sql = "INSERT INTO vix (date,close) VALUES ('".$date."','".$close."')";
Removing the concat operator (.) will result in the same.
There are two issues in your code.
As mentioned other mate you need to use quotes for Date string.
Second you can not use mysqli_multi_query() as like that.
Modified Code:
You can use multiple INSERT Statement as like that:
$o = file_get_contents("vixData.json");
$o = json_decode($o);
$date = [];
$close = [];
$set = $o->dataset->data;
foreach($set as $pos)
{
array_push($date,$pos[0]);
array_push($close,$pos[4]);
}
$sql = "";
foreach ($date as $key => $value) {
$sql .= "INSERT INTO vix (date,close) VALUES ('".$value."','".$close[$key]."'); ";
}
if (mysqli_multi_query($dbc, $sql)) {
echo "VIX Load Successful";
} else {
echo "VIX Load Error";
}
Remove the double quotes and concatinator wrapping your Values.
$sql = "INSERT INTO vix (date,close) VALUES ('$date','$close')";

keep a queries result array in storage in php

I am conducting a query whereby I am retrieving all rows from a db table where a certain column = 'xx'.
Then I need to store the array retrieved from the result.
Then I need to delete all those rows from the DB, but i still need to access the stored array AFTER carrying out the delete. It might sound a bit strange but this is what I need to do.
So far:
$Get_Appointments = "SELECT *
FROM TempSchedule2
WHERE CreatedBy = 'xx'";
$stmt = mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt, $Get_Appointments);
mysqli_stmt_execute($stmt);
if ($Apts = mysqli_stmt_get_result($stmt)){
$numRows = mysqli_num_rows($Apts);
echo 'numrows is '.$numRows.'<br>';
global $arrayToSave;
$arrayToSave = mysqli_fetch_array($Apts);
while($row=mysqli_fetch_array($Apts)){
//echo 'in the while?';
$scheduleID = $row['scheduleID'];
$DeleteApt_Query = "DELETE FROM tempschedule2 WHERE scheduleID = ?";
$stmt = mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt, $DeleteApt_Query);
mysqli_stmt_bind_param($stmt, "i", $scheduleID);
if (mysqli_stmt_execute($stmt)){
//executed
echo 'deleted';
}
else {
echo 'not deleted because '.mysqli_error($con);
$ErrorForLog = date("Y-m-d") . "\r\n" . mysqli_error($con). "\r\nInfo Attempted to delete apt id : " . $scheduleID. "\r\n\r\n";
error_log($ErrorForLog, 3, "Logs.txt");
}
}
echo 'savedArray here is ';
var_dump($arrayToSave);
What's happening is one row is not deleting for some reason. And then after the loop that executes the delete queries, I am var_dumping the global $arrayToSave (which i hoped was the entire array), and the result is that one element of the array which had not been deleted. So it seems as thought the global array is being modified within the loop? This is the first time I've had to use global in php so I'm probably not using it right.
Try this:
Change $arrayToSave = mysqli_fetch_array($Apts); to $arrayToSave = array();
Then add $arrayToSave[] = $row directly after the start of the while loop.
mysqli_fetch_array grabs the next row and turns it into an array. It doesn't take the whole result set and turn it into an array. That is why you put it in a while statement. That loops through ALL the rows. So loop through and save the results, then run your delete afterward.
$results = array();
while($row = mysqli_fetch_array($apts){
$results[] = $row;
}
//Now Delete
$DeleteApt_Query = "DELETE FROM tempschedule2 WHERE scheduleID = ?";
$stmt = mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt, $DeleteApt_Query);
mysqli_stmt_bind_param($stmt, "i", $scheduleID);
if (mysqli_stmt_execute($stmt)){
//executed
echo 'deleted';
} else {
echo 'not deleted because '.mysqli_error($con);
$ErrorForLog = date("Y-m-d") . "\r\n" . mysqli_error($con). "\r\nInfo Attempted to delete apt id : " . $scheduleID. "\r\n\r\n";
error_log($ErrorForLog, 3, "Logs.txt");
}
Also, you need to be careful running another query while you are still iterating through the result of a previous query. The data from the first query gets wiped out when you run another query.
global is useless in this place, you can safely delete it.
What you do is put the first retrieved row into $arrayToSave and iterate the over the rest of rows. What you probably want to do, is put all $rows into a two-dimensional array with something like $arrayToSave[] = $row; after the beginning of the while loop.
You fetch one row before the loop thereby removing it from the results $Apts:
$arrayToSave = mysqli_fetch_array($Apts);
So $arrayToSave only contains one row and that row is not looped over. You want to remove that and probably do something like this:
while($row=mysqli_fetch_array($Apts)){
$arrayToSave[] = $row;
Alternately use mysqli_fetch_all():
$arrayToSave = mysqli_fetch_all(($Apts);
foreach($arrayToSave as $row) {
//do stuff
}

php - Getting value from array in a for loop to use in MySQL

What I have is a custom admin page within Wordpress where the user can add names/titles/mp3's which all gets entered into the database. On the same page, I also have it select all the entries from the database and list them with checkboxes next to them and I'm trying to get it to delete the checked entries from the database using an array. This what I have so far:
$songs = $_POST['song'];
$num = count($songs);
for($i=0; $i < $num; $i++){
$sql = "DELETE FROM song_list WHERE title = '".$songs[]."'";
echo $sql;
var_dump($songs);
}
When I dump $songs, it has all the correct data, but when I try to pull it and add it to the query, I keep getting nothing. It's not an associative array, so I tried $songs[0] and $songs[1], but I get nothing.
Any insight would be appreciated, thank you.
EDIT:
var_dump
array(3) { ["Forget You"]=> string(2) "on" ["DJ Got Us Falling in Love"]=> string(2) "on" ["Blurred Lines"]=> string(2) "on" }
Also, I tried adding $i ($songs[$i]). It just comes out as title = ''
Your missing the array index:
$songs[$i]
Turns into:
$songs = $_POST['song'];
$num = count($songs);
for($i=0; $i < $num; $i++){
$sql = "DELETE FROM song_list WHERE title = '".$songs[$i]."'";
echo $sql;
}
An more elegant way is to use a foreach loop:
$songs = $_POST['song'];
foreach($songs as $song) {
$sql = "DELETE FROM song_list WHERE title = '".$song."'";
echo $sql;
}
An even more elegant way is to use prepared statements (with PDO):
// Prepare statement
$stmt = $dbh->prepare('DELETE FROM song_list WHERE title = :song');
$songs = $_POST['song'];
foreach($songs as $song) {
// Bind and execute
$stmt->bindParam(':song', $song);
$stmt->execute();
}
Just to make it much simpler and shorter - one-liner :)
$sql = "DELETE FROM song_list " .
"WHERE title IN ('" . implode("','", $_POST['song']) . "')";
Things to note:
Be aware of SQL injection attacks - never ever concatenate user input strings ($_GET, $_POST etc.) directly into SQL!
Deleting by title is very bad solution, because if you'll have in title for example symbol ', then your SQL will break. That's why in SQL id fields are invented :)
Adding $i to your array and you will get the value at the given place.
But you can write your code like this :
if(isset($_POST['song']) {
foreach($_POST['song'] as $key => $title) {
$sql = "DELETE FROM song_list WHERE title = '".$title."'";
echo $sql;
}
}

PHP array_sum function in codeigniter

The following code is a simple select statement that should use the array_sum function to return a value. The result should be getting stored in an array and then getting added up in the SUM function:
$this->db->select('period')
->from('calcdata');
$query = $this->db->get()->result_array();
$query = array_sum($query);
echo "SUM " . $query . "\n" ;
return $query;
the result of this is "SUM 0" but it should be 147 after adding all values up in the period column.
The following code works so i don't understand why the array would be any different from this:
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";
I am using codeigniter to create the arrays, does anyone know what is wrong here?
Thanks
Try calling the content of the field instead, not of the whole result array:
$this->db->select('period')->from('calcdata');
$query = $this->db->get();
$period_array = array();
foreach ($query->result_array() as $row)
{
$period_array[] = intval($row['period']); //can it be float also?
}
$total = array_sum($period_array);
UPDATE:
#uzsolt is right, I almost forgot there's a dedicated function in the Active Record class, select_sum(); you might want to try that out also, something like
$this->db->select_sum('period')->get('calcdata');
Quoting from the docs:
$this->db->select_sum();
Writes a "SELECT SUM(field)" portion for your query. As with
select_max(), You can optionally include a second parameter to rename
the resulting field.
$this->db->select_sum('age'); $query = $this->db->get('members');
//> Produces: SELECT SUM(age) as age FROM members

Categories