Load data from JSON file to MYSQL database - php

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')";

Related

How can I insert an array of variable into a database individually in php?

How can i insert the array into the database individually, It's displaying error. I want to insert them all at once... sometimes the array may be more the 3, 5 or 10.
$roll_num = '111,222,333';
$rollnum = explode(",",$roll_num);
$sql ="INSERT INTO eyfstb(specialnum) VALUES('$rollnum[]')";
if($db->query($sql)== TRUE){
echo "true";
}else{
echo "false";
}
You can Insert it Dynamically to your Database and this will fix your problem. :D
$roll_num = '111,222,333';
$rollnum_arr = explode(",",$roll_num);
for($x = 0; $x < count($rollnum_arr); $x++){
$sql ="INSERT INTO eyfstb(specialnum) VALUES(".$rollnum_arr[$x].")";
}
if($db->query($sql) == TRUE){
echo "true";
}else{
echo "false";
}
The explode function converts your array into a multiple index variables, so regarding your question, it should be:
$roll_num = '111,222,333';
$rollnum = explode(",",$roll_num);
$sql ="INSERT INTO eyfstb(specialnum) VALUES('$rollnum[0]')";
if($db->query($sql)== TRUE){
echo "true";
}else{
echo "false";
}
If you want to insert all of them, you could either store it as a JSON in your table, or create additional columns.
Firt of all, your $roll_num variable is not an array.
And the explode function will split your string by a string as it said here: https://www.php.net/manual/en/function.explode.php
For that you could build your array whith your values inside like:
$roll_num = array('111', '222','333');
And INSERT INTO thanks to a loop:
for ($i = 0; $i < count($roll_num); $i++) {
$sql = "INSERT INTO eyfstb(specialnum) VALUES(" . $roll_num[$i] . ")";
$db->query($sql);
$db->execute();
}
It should work :)
As I understand you want to insert a new row for each array cell. To do so, I would recommend:
$roll_num = '111,222,333';
$rollnum = explode(",", $roll_num);
$sql = "INSERT INTO eyfstb(specialnum) VALUES('" . implode("'),('", $rollnum) . "')";
That will produce the following SQL:
INSERT INTO eyfstb(specialnum) VALUES('111'),('222'),('333')
And will be more efficient than looping and inserting every iteration.

How to insert infinite records in mysql from php?

I have to insert multiple records in mysql from php. How to pass list to mysql table.Please suggest your solution.
$course[0] = 1;
$course[1] = 'test';
$course[2] = 'test1'
$sql = "INSERT INTO temp_course(uniqueId,fullName,shortName) VALUES($course[0],'$course[1]','$course[2]')";
i tried like above. but values not inserted.
#Gopal you can try with implode() but make sure your array sequence must be same as your table column sequence given by you in query, try like below:
<?php
$course[0] = 1;
$course[1] = 'test';
$course[2] = 'test1';
$sql = "INSERT INTO temp_course(uniqueId,fullName,shortName) VALUES(".implode(',', $course).")";
Try wrapping the variables with curly brackets like this:
$course = [];
$course[0] = 1;
$course[1] = 'test';
$course[2] = 'test1';
$sql = "INSERT INTO temp_course(uniqueId,fullName,shortName) VALUES($course[0],'$course[1]','$course[2]')";

Insert PHP Arrays as MYSQL columns

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, ',');

MySQL SELECT query seems to skip spaces

I'm a beginner with PHP and mySQL and I'm using it for my project. I sort of have a problem with my query.
This is my code:
$doctname = mysql_query("SELECT name_of_doctor FROM {$table} WHERE department_no = '{$_REQUEST['deptno']}'");
$doctnamerow = mysql_fetch_row($doctname);
do
{
foreach ($doctnamerow as $cell)
{
$doctnamerowvalue = $cell;
}
} while ($doctnamerow = mysql_fetch_row($doctname));
So the problem I have is that if the doctor's name has a space between it (e.g "AJ Ramos") then it seems to skip the space and just returns "AJ" and not the surname. How do I do this? Thanks =)
edit:
Silly me, It was just an error with my code, I was using $doctnamerowvalue as a value=$doctnamerow for one of my text boxes and forgot to put double quotes, which resulted in value=doctor name and not value="doctor name". Sorry
Flash Code Review:
mysql_* is deprecated. Use MySQLi or PDO.
Your code is wide open to SQL injection
$doctornamerowvalue is overwritten on every iteration
the foreach you are doing is pointless.
variable names are poorly chosen.
Here it is refactored:
// do these in a config file !!!
$db = new PDO('mysql:dbname=' . DB_NAME . ';host=localhost', DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); // if you want to use associative arrays
// here is the refactored code
$query = "SELECT name_of_doctor FROM `{$table}` WHERE department_no = :deptno";
$stmt = $db->prepare($query);
$stmt->execute(array(':deptno' => $_REQUEST['deptno']));
$doctors = $stmt->fetchAll();
foreach ($doctors as $doctor) {
echo $doctor['name_of_doctor'] . '<br>';
}
Related to your 'bug'
Check the table structure and data. It's possible that the field contains only the surname, and there is another field that contains the name.
Check the table length - maybe it's too small, so the string is truncated.
try this:
$sql = "your sql syntax";
$result = mysql_query($sql);
$array_of_things = array();
while ($row = mysql_fetch_array($result)) {
$array_of_things[] = $row['table_column_name'];
}
foreach($array_of_things as $val) {
echo $val;
}
used this :
$doctname = mysql_query("SELECT name_of_doctor FROM {$table} WHERE department_no = '{$_REQUEST['deptno']}'");
$doctnamerow = mysql_fetch_row($doctname);
while ($raw = mysql_fetch_row($doctname)) {
echo $raw['name_of_doctor'];
}

Compare values from array mysql php [duplicate]

This question already has answers here:
Passing an array to a query using a WHERE clause
(17 answers)
Closed 1 year ago.
Hi I'm trying to compare values from 2 arrays with this query, which is the only way I know:
$session = "1,2,3,"
$table_name = "table1";
$column_name = "data1"; // value for test is 1,4,5,
$sql = "";
$sql .= "SELECT * FROM $table_name WHERE ";
$franquia = array();
$franquia = explode(",", $session);
if (!empty($franquia)) {
$final_id = array();
foreach ($franquia as $val) {
if (trim($val) != '') {
$final_id[] = $val;
}
}
$count_data = count($final_id);
foreach ($final_id as $key => $id) {
if ($id > 0) {
$sql .= " $id IN ($column_name) ";
if ($key < $count_data - 1) {
$sql .= "OR ";
}
}
}
}
echo $sql;
I have values 1,2,3 on $session and 1,4,5on $data1 so the comparison between $session and $data1 was suposed to return true due to both of them have value 1, but I don't get any results.
Actually it only works if both arrays are the same, like $session = 1,2,3 and $data1 = 1,2,3
What am I doing wrong?
You are using the IN clause wrong; In a nutshell, instead of
WHERE value IN (column)
The correct usage is:
WHERE column IN (value, value, value)
Which in turn will not help with what you are trying to do (more about the IN clause). Rather, try the following:
foreach ($final_id as $key => $id) {
if ($id > 0) {
$sql .= "$column_name LIKE %$id,%";
if ($key < $count_data - 1) {
$sql .= "OR ";
}
}
}
}
This should work, but there are a couple things you should be aware of. First you probably are vulnerable to SQL Injections, and second you should consider either using a different scheme with your data in your DB, since using LIKE %% to search for numeric values is a waste, or fetch in advance the entry from the DB and search in the resulting string. Consider the code above nothing but a quick and dirty hack that you should rather avoid :)

Categories