I'm working on a project that involves a PHP script that calls an API and gets a JSON array. I then want to put this JSON array into a MySql database. The issue I am running into is that while the script executes without any errors or exceptions in the terminal, my database is not filling with any data.
I am running MySQL Workbench as my MySQL client and have created a schema called "team_data" into which I am attempting to input my JSON array. I have removed my API key for obvious reasons. Any ideas where I am going wrong here?
<?php
$con = mysql_connect("127.0.0.1","XXXXXX","XXXXXX") or die('Could not connect: ' . mysql_error());
mysql_select_db("test1", $con);
$json = file_get_contents('team_data.json');
$data = json_decode($json, true);
foreach($data as $row)
{
$game = $data['nfl_game_id'];
$team = $data['team'];
$opponent = $data['opponent'];
$totfirstdown = $data['totalfirstdown'];
$totyds = $data['totyds'];
$pyds = $data['pyds'];
$ryds = $data['ryds'];
$pen = $data['pen'];
$penyds = $data['penyds'];
$trnovr = $data['trnovr'];
$pt = $data['pt'];
$ptyds = $data['ptyds'];
$ptavg = $data['ptavg'];
$sql = "INSERT INTO Teams(nfl_game_id, team, opponent, totalfd, totyds, pyds, ryds, pen, penyds, trnovr, pt, ptyds, ptavg);
VALUES('$game', '$team', '$opponent', '$totfirstdown', '$totyds', '$pyds', '$ryds', '$pen', '$penyds', '$trnovr', '$pt', '$ptyds', '$ptavg')";
mysql_query($sql,$con);
}
?>
Error from your comment, after I suggested you check for errors on your query:
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('', '', '', '', '', '', '', '', '', '', '', '', '')' at line 1
The error shows you where it starts right syntax to use near '; < right there.
... ptyds, ptavg); < see that semi-colon? Remove it. It's an end of statement character.
However, you're doing foreach($data as $row) but not using $row.
You need to change all $data['xxx'] to $row['xxx'] which is why your values are empty.
If there are any characters that MySQL will complain about, then you will need to escape your data. Any which way, it's best that you do.
As a bonus answer:
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
First let's see whether your command successfully retrieved the JSON data.
var_dump($data);
Let's place that right after the line where we json_decode the data.
If the JSON data looks good in our array, then the next thing for us to check would be the SQL (maybe there are required columns that aren't receiving values or other constraint, etc.)
Related
I am posting data for event in this format via ajax:
doctor=100&date=2015-04-30&rCheck=1&rDate=2015-05-12&fromTime=21%3A35&toTime=22%3A40&status=open
I am getting it like this with php
$date = $_POST['date'];
$fromHours = $_POST['fromHours'];
$fromMinutes = $_POST['fromMinutes'];
$toHours = $_POST['toHours'];
$toMinutes = $_POST['toMinutes'];
$fromTime = $_POST['fromTime'];
$toTime = $_POST['toTime'];
$start = $date.' '.$fromTime.':00';
$end = $date.' '.$toTime.':00';
$status = $_POST['status'];
$doctor = $_POST['doctor'];
if($_POST['rCheck']==1){
$repeat = $_POST['rDate'];
}else{
$repeat = '0000-00-00';
}
When I echo any of that variables I get correct result.
I am inserting data in database like this:
$query = 'INSERT INTO events (start,end,doctor,status,repeat) VALUES ("'.$start.'","'.$end.'","'.$doctor.'","'.$status.'","'.$repeat.'")';
$result = mysqli_query($db, $query) or die (mysqli_error($db));
Now main problem is $repeat because without it everything is inserted without problem but with $repeat I get this error:
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 'repeat) VALUES ("2015-04-30 21:35:00","2015-04-30 22:40:00","100","offen","2015-' at line 1
Insert stops after fifth '-' character. Even if $repeat is 0000-00-00
Field for that in database is date field in format 0000-00-00
I really don't know where problem is.
Thank you for helping.
repeat is a MySQL reserved word
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Either rename it to something else; for example "repeats", or use ticks around it
(start,end,doctor,status,`repeat`)
Look at what MySQL is telling you; it's pointing it out where it starts:
...for the right syntax to use near 'repeat
^
Sidenote:
If you're still having problems inserting data into your table, you can sanitize your input(s) using mysqli_real_escape_string() or using prepared statements as stated below.
I need to point out though, that your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they're much safer.
I working in a php application where I must delete the selected items from a list where each item haves their own ID from mysql database, everything goes ok until execute the query in php.
This is the error message:
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 '' at line 5
this is the String that I execute in the query:
$queryDE = "delete from md5_agenda
where id_empresa = $empi
and id_unidade = $unii
and id_usuario = $usrr
and id_item_agenda in ($deletar);"
The variable $deletar receives their value from post method and their value is like: 35,36,47,... and can be one ore many different values
But my problem is if I change $deletar for the exactly values everything goes fine, but if I use the php variable with THE EXACTLY SAME VALUE it doesn't work and returns the previous error message, I have no more ideas about what to do... I wanna keep in this way where I can choose all IDs that I want delete, without repeat the query.
Thanks.
edit:
foreach($deletar as $val)
{
$queryDE = "delete from md5_agenda
where id_empresa = $empi
and id_unidade = $unii
and id_usuario = $usrr
and id_item_agenda = $val;"
}
your code is not working because $deleter is return multiple value.
check code it's working.
Why don't you use a safe parametrized query?
$db =new PDO('... your connection string ... ');
$stmt = $db->prepare("delete from md5_agenda
where id_empresa = :empi
and id_unidade = :unii
and id_usuario = :usrr
and id_item_agenda in (:deletar);");
$stmt->execute(array(
':empi' => $empi,
':unii' => $unii,
':usrr' => $usrr,
':deletar' => $deletar
)
);
I want to insert a record with an apostrophe into a MySQL database using PHP. Following is my code:
$importer_name =mysql_escape_string ($objWorksheet->getCellByColumnAndRow(1,3)->getValue());
$exporter_name = $objWorksheet->getCellByColumnAndRow(1, 3)->getValue();
$prod_quantity_unit = $objWorksheet->getCellByColumnAndRow(1,6)->getValue();
$prod_fob_value = $objWorksheet->getCellByColumnAndRow(5,6)->getValue();
$prod_quantity = $objWorksheet->getCellByColumnAndRow(1,8)->getValue();
$prod_fob_unit= $objWorksheet->getCellByColumnAndRow(5,8)->getValue();
$prod_gross_waight= $objWorksheet->getCellByColumnAndRow(1,10)->getValue();
$prod_cif_value= $objWorksheet->getCellByColumnAndRow(5,10)->getValue();
$prod_net_weight= $objWorksheet->getCellByColumnAndRow(1,12)->getValue();
$prod_cif_unit_price= $objWorksheet->getCellByColumnAndRow(5,12)->getValue();
$prod_brand= $objWorksheet->getCellByColumnAndRow(5,14)->getValue();
$hs_code = $objWorksheet->getCellByColumnAndRow(1,17)->getValue();
$shipping_date = $objWorksheet->getCellByColumnAndRow(5,17)->getValue();
$customs = $objWorksheet->getCellByColumnAndRow(1,19)->getValue();
$transport_company = $objWorksheet->getCellByColumnAndRow(5,19)->getValue();
$country_of_origin = $objWorksheet->getCellByColumnAndRow(1,21)->getValue();
$transport_mode = $objWorksheet->getCellByColumnAndRow(5,21)->getValue();
$country_of_trade = $objWorksheet->getCellByColumnAndRow(1,23)->getValue();
$hs_code_description = $objWorksheet->getCellByColumnAndRow(1,26)->getValue();
$product_description = $objWorksheet->getCellByColumnAndRow(1,28)->getValue();
$insertquery="INSERT INTO tb_peru_data
(importer_name,exporter_name,product_quantity_unit,
product_fob_unit,product_quantity,product_fob_value,
product_gross_weight,product_cif_value,
product_net_weight,product_cif_unit_price,
product_brand,shipping_hs_code,shipping_date,
shipping_customs,shipping_transport_company,
shipping_country_of_origin,shipping_transport_mode,
shipping_country_of_trade,hs_code_description,
product_description)
VALUES
('$importer_name','$exporter_name','$prod_quantity_unit',
'$prod_fob_unit','$prod_quantity','$prod_fob_value',
'$prod_gross_waight','$prod_cif_value','$prod_net_weight',
'$prod_cif_unit_price','$prod_brand','$hs_code','$shipping_date',
'$customs','$transport_company','$country_of_origin',
'$transport_mode','$country_of_trade',
'$hs_code_description','$product_description')";
mysql_query($insertquery)or die('ErrorrPERU: '.mysql_error());
/*$del="DELETE * FROM tb_excel_file";
mysql_query($del);*/
?>
This does not work, and gives the following error:
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
's','12U','6','9','54',
'34.83','55.5','31.83','6.17','','7323931000','2008/04/1' at line 3
Use mysqli_real_escape_string instead of deprecated mysql_real_escape_string
This function will force you to input mysql table / database.
This way your collation will be considered while escaping
You can use real_escape_string() in PHP. You need to escape the apostrophe (that is, tell SQL that the apostrophe is to be taken literally and not as the beginning or end of a string). To add more, I'd say that you can also use PDO, but consider using addslashes($string) and stripslashes($string).
I get the message:
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
'12:00,25.32,1015.19,42.32,200.0,1.29,2.25,7.11,11.58,5.97,3.5,0.0,0.0,0.0,0.0,37'
at line 2
relevant code:
$con = mysql_connect("127.0.0.1", "username", "password") or die(mysql_error());
mysql_select_db("database",$con) or die (mysql_error());
//readFmi() returns an array of strings with values separated by commas
$array = readFmi($xml);
$cols = 'date, Temperature, Pressure, Humidity, WindDirection, WindSpeedMS,
MaximumWind, WindGust, DewPoint, TotalCloudCover, LowCloudCover, MediumCloudCover,
HighCloudCover, Precipitation1h, PrecipitationAmount, RadiationLW, RadiationGlobal,
RadiationNetTopAtmLW';
foreach($array as $a){
$a2 = mysql_real_escape_string($a);
echo $a2."<br>";
mysql_query("INSERT INTO forecastsFMI ($cols)
VALUES ($a2)") or die (mysql_error());
}
mysql_close($con);
$a when printed looks like this
2013-06-24 12:00,25.32,1015.19,42.32,200.0,1.29,2.25,7.11,11.58,5.97,3.5,0.0,0.0,0.0,0.0,375.85,550.09,-260.6
$cols are the exact same ones as found in the table in the database, I set them all to be varchar for now, while trying to figure out where i have made my mistake(s). I have been counting the fields in the db and values to see if that is where i have gone wrong, tried to change the format of the string itself and tried to change and tweak different parts of the code, without any difference in result. What might cause this?
Thank you
//Tobias
You need to add quotes around string/date column values in string. So in you case specially you need something like.
"2013-06-24 12:00",25.32,1015.19,42.32,200.0,1.29,2.25,7.11,11.58,5.97,3.5,0.0,0.0,0.0,0.0,375.85,550.09,-260.6
I'm trying to insert some data into my mysql database. The connection is working fine but im having a problem with sending the query correctly to the database. Below you can find the code in my php file. I also post what for type of fields they are in the Database.
Fields in the mysql database:
Reservaties_id = int
Materialen_id = int
aantal = int
effectief_gebruikt = tinyint
opmerking = Varchar2
datum_van = date
datum_tot = date
$resID = $_REQUEST['resID'];
$materialen_id = $_REQUEST['materialen_id'];
$aantal = $_REQUEST['aantal'];
$effectief_gebruikt = $_REQUEST['effectief_gebruikt'];
$opmerking = $_REQUEST['opmerking'];
$datum_van = date('YYYY-MM-DD',$_REQUEST['datum_van']);
$datum_tot = date('YYYY-MM-DD',$_REQUEST['datum_tot']);
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`, `materialen_id`, `aantal`, `effectief_gebruikt`, `opmerking`, `datum_van`, `datum_tot`) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', $datum_van, $datum_tot)";
mysql_query($string);
you have to include single quotes for the date fields '$dataum_van'
$string = "INSERT INTO `materialen_per_reservatie`(reservaties_id, materialen_id, aantal, effectief_gebruikt, opmerking, datum_van, datum_tot) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')";
and this is only a example query, while implementing don't forget to sanitize your inputs
Your code has some serious problems that you should fix. For one, it is not doing any error checking, so it's no surprise the query breaks silently when it fails. Check for errors and it will tell you what goes wrong - how to do it is outlined in the manual on mysql_query() or in this reference question.. Example:
$result = mysql_query($string);
// Bail out on error
if (!$result)
{
trigger_error("Database error: ".mysql_error(), E_USER_ERROR);
die();
}
In this specific case, I'm fairly sure it's because you are not putting your values into quotes after the VALUES keyword.
Also, the code you show is vulnerable to SQL injection. You need to escape every value you use like so:
$resID = mysql_real_escape_string($_REQUEST['resID']);
for this to work, you need to put every value in your query into quotes.
try this
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`) VALUES ('".$resID."')";