MySQL Insert error with null values - php

So i'm trying to insert data into a MySQL table from an array that contains multiple arrays which hold data for each row of a table using the code below:
if (is_array($tbl_data)){
$sql = "INSERT INTO teshsting (agent, event , data1,data2,data3,data4,data5) values ";
$arrayValues = array();
foreach ($tbl_data as $row){
$agent = mysql_real_escape_string($row[0]);
$event = mysql_real_escape_string($row[1]);
$data1 = mysql_real_escape_string($row[2]);
$data2 = mysql_real_escape_string($row[3]);
$data3 = mysql_real_escape_string($row[4]);
$data4 = mysql_real_escape_string($row[5]);
$data5 = mysql_real_escape_string($row[6]);
$value = "($agent,$event,$data1,$data2,$data3,$data4,$data5)";
array_push($arrayValues, $value);
}
$sql .=implode(',', $arrayValues);
Quick check using var_dum($sql) produces the following:
INSERT INTO teshsting (agent, event , data1,data2,data3,data4,data5) values (NONE,QUEUESTART,,,,,)/////
The above Sql is invalid due to the multiple commas here :(NONE,QUEUESTART,,,,,)which are generated by empty fields. How can I insert single quotations inside the query to make it valid ? i.e the correct sql syntax:
INSERT INTO teshsting (agent, event , data1,data2,data3,data4,data5) values (NONE,QUEUESTART,'','','','','')

Either:
$data1 = "'" . mysql_real_escape_string($foo) . "'";
or
$value = "(...,'$data1',...)";
Just don't try both options, which would give you (...,''$data1'',...) and kill the query with syntax errors.

Related

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

PHP - Upload data to database using a loop

I have an array which contains $player_ids. The array was obtained in a form which the user used to select his team. I then query the database with the $player_ids array.
As such:
if ( isset($_POST['submit']) ) {
$player_ids = array_map('intval', $_REQUEST['players']);
var_dump($player_ids);
$query = 'SELECT `name`
FROM `player_info`
WHERE `player_id` IN (' . implode(',', $player_ids) . ')';
$return_names = mysql_query($query) or die(mysql_error());
while ( $row = mysql_fetch_assoc($return_names) ) {
$selected[] = $row['name'];
}
var_dump($selected);
The above code is working and when I open it in my browser I get this output
Now I want to extract the values from array $selected (which contains the names of players selected) and upload it to a database. I try to do this as follows:
foreach ($selected as $player){
$sql = mysql_query('INSERT INTO `team`(`player_name`) VALUES ("$player")')
or die(mysql_error());
print ($player);
echo'<br>';
` }
Im suspecting the above code is where the problem comes in. when the above code is executed the database contains only the array name itself and not the actual values of the array. As the following picture shows:
If anyone could point me in the right direction, as to why the array name and not its values gets saved in the database it would be greatly appreciated.
Thanks in advance.
You must put double quotes around your string instead of single quotes. In single quoted strings variables like $player are not replaced by their value interpreted there as text.
use this:
'INSERT INTO `team`(`player_name`) VALUES ("' . $player . '")'
instead of this:
'INSERT INTO `team`(`player_name`) VALUES ("$player")'
Just replace following code with your ones code and it will work efficiently.
foreach ($selected as $player){
$sql = mysql_query("INSERT INTO `team`(`player_name`) VALUES ('$player')")
or die(mysql_error());
echo "$player<br />";
}

Error in Array to string conversion

I have a query that's retraive a list of id's. Those id's are in an array and i need to save it in table with those id's. I tried using implode to make those id's a string i could use in a where clause but i keep getting this error.
$save_food = $_POST['save_food'];
$unserializedData = array();
parse_str($save_food,$unserializedData);
foreach($unserializedData as $unserializedData1){
$query = mysql_query("insert into subscribefood (s_user_id,s_food) values ('$ft_user_id','".implode($unserializedData1, ',')."')");
}
Try this
<?php
$save_food = $_POST['save_food'];
$unserializedData = array();
parse_str($save_food,$unserializedData);
$datalist = $unserializedData['foodtype'];
foreach($datalist as $data){
$query = mysql_query("insert into subscribefood (s_user_id,s_food) values ('$ft_user_id','$data')");
}
?>

implode() array to insert record into mySql database

I have a single row in a PHP array and I would like to insert that row into mySQL database by imploding the keys and values into a string and using those strings in my Insert statement as follows:
$fields = implode(",", array_keys($_POST));
$newdata = implode(",", $_POST);
$query = (
"INSERT INTO Food_entered ($fields)
VALUES ('$newdata')");
$result = mysqli_query($dbc, $query);
I am able to create the strings, and they appear to be in proper form ,however the row is not being inserted. Seems like a simple approach but not sure what I'm missing.
As #Barmar has pointed out, the problem is your quotes are on the outside of your variable.
I think this may be an easier to follow/cleaner way of fixing this however than the method Barmar posted:
$newdata = "'" . implode("','", $_POST) . "'";
You need to quote each value, not the entire list of values:
$fields = implode(",", array_keys($_POST));
$newdata = implode(",", array_map(function($x) use ($dbc) {
return "'" . $dbc->real_escape_string($x) . "'";
}, $_POST));
$query = (
"INSERT INTO Food_entered ($fields)
VALUES ($newdata)");
$result = mysqli_query($dbc, $query);

Build SQL Select a better way ? (Oracle)

i have the following code part in one of my classes:
$l = new Location();
$result = $l->getLocIdsbyCity($city); // returns csv
$ids = explode(',', $result);
$where = 'LOC_ID = ' . $ids[0];
unset($ids[0]);
foreach ($ids as $id) {
$where .= ' OR LOC_ID = ' . $id;
}
$select->where($where);
Is there an more "elegant" way to build the select stmt? I need all records with one of the provided ids..
Assuming your csv is injection safe (contains trusted values and no user-provided input):
$l = new Location();
$result = $l->getLocIdsbyCity($city); // returns csv
$where = "LOC_ID IN ($result)";
$select->where($where);
If it's not, you should explode it, mysql_real_escape_string each value and implode back.
You can use the in operator to form a condition like:
where LOC_ID in (1,2,3,4,5)
If you are sure that $result can't contain anything harmful, you should be able to use it directly without having to split it and loop.

Categories