mysql database SQL syntax error php - php

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

Related

JSON Array to MySQL Database

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.)

Convert sql result (object) to string variable for future input into sql table (I do not want to echo the result)

I have read most of the questions here and read the php manual in regards to the problem of converting an sql result to a string, however none of them is working for me. The examples given I understand, however they are echoing the sql results, I do not want the result to be echoed, I just want it to be stored in a variable so I can immediately insert it into a next sql table.
This is my code:
$cnt_fips = mysqli_query($con, "SELECT cc_fips FROM location2 WHERE location_name = '$cnt'");
$row = mysqli_fetch_assoc($cnt_fips);
These are the codes I have used to convert to string but failed with
$myStr = !is_array($row) ? trim(addslashes($row)):'';
and
$myStr = (string)$row;
and
$myStr = print_r($row,true);
and also
$myStr = (string)$row;
And insert into the table below
$query2 = mysqli_query($con, "INSERT INTO location3 VALUES ('','$myStr')");
$row is always an array with column names as the keys, use:
$myStr = $row['cc_fips'];
Also, I'm pretty sure you can do that all in one insert with a sub-select (though maybe not if a row with $cnt doesn't exist). If so, maybe someone will post it.

PHP INSERT into creates Database error

I am attempting to create a function that will insert items (and will do the same to edit) items in a database through a form. I have the form and the PHP - and when I run the function, I get the correct database name to pull and the variable names to pull along with the values I input, but I then see a database error? Any help would be great (I'm still newer to PHP really and pulling out some hair)
Config File:
$hostname = 'localhost';
$username = 'DEFINED';
$password = 'DEFINED';
$database = 'DEFINED';
$table = 'recipes';
require('../config.php');
$link = mysql_connect($hostname,$username,$password);
mysql_select_db($database,$link);
/* Get values and submit */
$rid = mysql_real_escape_string($_POST['rid']);
$name = mysql_real_escape_string($_POST['name']);
$category = mysql_real_escape_string($_POST['category']);
$tags = mysql_real_escape_string($_POST['tags']);
$search_tags = mysql_real_escape_string($_POST['search_tags']);
$description = mysql_real_escape_string($_POST['description']);
$description2 = mysql_real_escape_string($_POST['description2']);
$recipeAbout = mysql_real_escape_string($_POST['recipeAbout']);
$ingredients_1 = mysql_real_escape_string($_POST['ingredients_1']);
$directions_1 = mysql_real_escape_string($_POST['directions_1']);
$query = "INSERT INTO $table (name, category, tags, search_tags, description,description2, recipeAbout, ingredients_1,directions_1) VALUES ('$name','$category','$description','$description2' $tags','$search_tags','$description','$recipeAbout','$ingredients_1','$directions_1')";
echo $query;
Besides the missing comma in '$description2' $tags' => '$description2', $tags' which you said had been added afterwards, and signaled by Ryan: there's also a missing quote, so change it to '$description2', '$tags' and having 2x '$description' variables, remove one.
VALUES
('$name','$category','$tags','$description','$description2', '$search_tags','$recipeAbout','$ingredients_1','$directions_1')";
However, the most important part to querying, is that you must use mysql_query() which you are not using => mysql_query() which is why data isn't being inserted, once you've fixed the syntax errors.
mysql_query() is the essential part.
Add the following to your code:
if(mysql_query($sql,$link)){
echo "Success";
}
else{
echo "Error" . mysql_error();
}
Plus, use prepared statements, or PDO with prepared statements.
You're using a deprecated library and open to SQL injection..
Plus make sure you have assigned $table to the table you wish to enter data into. It's not shown in your question.
You also did not show what your HTML form contains. Make sure that you are using a POST method and that all elements are named with no typos.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Sidenote: Error reporting should only be done in staging, and never production.
EDIT: and using mysqli_
As a quick test, try the following and replacing the values in the line below with your own.
<?php
$link = mysqli_connect("host","username","password","database")
or die("Error " . mysqli_error($link));
$table = "recipes";
$name = mysqli_real_escape_string($link,$_POST['name']);
mysqli_query($link,"INSERT INTO `$table` (`name`) VALUES ('".$name."')")
or die(mysqli_error($link));
?>
If that still does not work, then you need to check your database, table, column name(s), including types and column lengths.
Lot's of stuff wrong here...
You're missing a quote on the second of these two items, as well as either a string concat or a comma: '$description2' $tags'
You've also got your order messed up for tags, search tags, and description 1/2.
$description is in there twice (you have 9 columns defined and 10 values in your statement)
You don't seem to have declared a value for $table
As Fred -ii- has pointed out in his answer, you're missing mysql_query() to actually run it. I assumed you have it further down in your code, but it's missing from the post, which is causing some confusion...
Also, consider updating to use mysqli instead of mysql functions.
what are you echoing $query for?
You do not have any reason to do that except if you just want to use it as a string variable.
it should be mysql_query($query);
What is the exact "database error" error you are getting?
I suggest reading this article about PDO
If you can't insert the data correctly, this might be your problem too.

unable to insert into mysql database using php

$db = mysql_connect("localhost","root","123");
mysql_select_db("website_categorization") or die("\n error selecting database" );
$keyword_array = preg_split('/[\s,]+/', $tag);
foreach($keyword_array as $tag1)
{
mysql_query("INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,$tag1)");
}
echo "\nAffected rows are ".mysql_affected_rows()."\n";
mysql_close($db);
Can u tell me what is the problem with this code??...I intend to insert rows into the category_keyword table from an array $keyword_array. I get errors "Affected rows are -1" and insertion does not work
You should quote and escape string values.
You should also handle errors, to be notified of them.
You should also write distinct statements, to be able to read your code later (as well as let others to read it).
$tag1 = mysql_real_escape_string($tag1);
$sql = "INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,'$tag1')";
mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
insert multiple rows via a php array into mysql
You need to encapsulte the string $tag in a query, otherwise mysql will think its a column name
mysql_query("INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,'".mysql_real_escape_string($tag1)."')");
You should quote and escape your string columns
$tag1 =
mysql_real_escape_string($tag1);
mysql_query("INSERT INTO
category_keyword(ID_Category, Keyword)
VALUES(2,'$tag1')");
You should also handle the mysql query errors to know why the query get failed. With the current code you never know why it is failing.It is better to handle mysql errors.
mysql_query('Your query') or trigger_error(mysql_error());
You can use this:
mysql_query("INSERT INTO category_keyword SET ID_Category=2, Keyword=".$tag1.");
Better syntax to understand :)

Read tab delimited text file into MySQL table with PHP

I am trying to read in a series of tab delimited text files into existing MySQL tables. The code I have is quite simple:
$lines = file("import/file_to_import.txt");
foreach ($lines as $line_num => $line) {
if($line_num > 1) {
$arr = explode("\t", $line);
$sql = sprintf("INSERT INTO my_table VALUES('%s', '%s', '%s', %s, %s);", trim((string)$arr[0]), trim((string)$arr[1]), trim((string)$arr[2]), trim((string)$arr[3]), trim((string)$arr[4]));
mysql_query($sql, $database) or die(mysql_error());
}
}
But no matter what I do (hence the casting before each variable in the sprintf statement) I get the "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 1" error.
I echo out the code, paste it into a MySQL editor and it runs fine, it just won't execute from the PHP script.
What am I doing wrong??
Si
UPDATE: Here are the echoe'd SQL's:
INSERT INTO wheelbase (WheelBaseCode, LanguageCode, WheelBaseDescription) VALUES ('A1', 'GBEN', '2.50-2.99m')
INSERT INTO wheelbase (WheelBaseCode, LanguageCode, WheelBaseDescription) VALUES ('A2', 'GBEN', '3.00-3.49m')
INSERT INTO wheelbase (WheelBaseCode, LanguageCode, WheelBaseDescription) VALUES ('A3', 'GBEN', '3.50-3.99m')
INSERT INTO wheelbase (WheelBaseCode, LanguageCode, WheelBaseDescription) VALUES ('A4', 'GBEN', '4.00-4.49m')
Interestingly, I now have it creating the correct number of rows in the table, but the values it inserts are empty...
Could this be an encoding issue in the source text file??
You don't need the string cast, the data will already be strings.
Make sure there are no quotes in the file data. Echo out the sql string before you run it to see if there's something obviously wrong.
Change the SQL to:
"INSERT INTO my_table (`field1Name`, `field2Name`, `field3Name`, `field4Name`, `field5Name`) VALUES('%s', '%s', '%s', '%s', '%s');"
This change includes the field names, and quoting the last two values.
I dont like you method in general. Maybe you fix your "first" problem with the missing
rows. Whats about some special character like '" backslash or SQL injection?
I think you should use prepared statements which PDO provides and call the "bindValue" of
the statement. It is a stable and buildin PHP lib. Or you can use dbTube.org instead
which is a graphical import tool.
Greeting
Shutter
From PHP.net:
<?php
fputcsv($fp, $foo, "\t");
?>
you just forgot that single quotes are literal...meaning whatever you put there that's what will come out so \t would be same as t because \ in that case would be only used for escaping but if you use double quotes then that would work.

Categories