Below I am getting a syntax 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 'call, county, id, location, callcreated, station, units, calltype, lat, lng) VAL' at line 1, and cant figure out why! Any help would be greatly appreciated!
<?php
mysql_connect("localhost", "test", "test") or die(mysql_error());
mysql_select_db("firecom") or die(mysql_error());
$data = file_get_contents("http://208.71.205.35/PITS/");//thanks WCCCA!
$pattern = "/id=\"hidXMLID\" value=\"([^\"]+)\"/";//looking for the rnd xml id#
preg_match_all($pattern, $data, $xmlext);
$url = "http://208.71.205.35/PITS/xml/fire_data_" . $xmlext[1][0] . ".xml";//putting together the secret xml url
$xml = simplexml_load_file($url);
foreach ($xml->marker as $element) {
$lat = $element->attributes()->lat;
$lng = $element->attributes()->lng;
$countydirty = $element->AGENCY;// gets agency
$wcccanumberdirty = $element->CALL_NO;
$iddirty = $element->TWO_DIGIT_CALL_NO;// gets call id#
$calldirty = $element->CALL_TYPE_FINAL_D;// gets call type
$locationdirty = $element->LOCATION;// gets location
$callcreateddirty = $element->CALL_CREATED_DATE_TIME;
$stationdirty = $element->BEAT_OR_STATION;// get first marker station
$unitsdirty = $element->UNITS;// get first marker units
$calltypedirty = $element->TYPE;
//this next section removes the "~" from the start of all the lines
$county = str_replace('~','',$countydirty);
$wcccanumber = str_replace('~','',$wcccanumberdirty);
$id = str_replace('~','',$iddirty);
$call = str_replace('~','',$calldirty);
$location = str_replace('~','',$locationdirty);
$callcreated = str_replace('~','',$callcreateddirty);
$station = str_replace('~','',$stationdirty);
$units = str_replace('~','',$unitsdirty);
$calltype = str_replace('~','',$calltypedirty);
mysql_query("INSERT INTO calls (wcccanumber, call, county, id, location, callcreated, station, units, calltype, lat, lng) VALUES('$wcccanumber', '$call', '$county', '$id', '$location', '$callcreated', '$station', '$units', '$calltype', '$lat', '$lng')") or die(mysql_error());
echo "$call - $county - $wcccanumber - $id - $location - $callcreated - $station - $units - $calltype <br />";
}
?>
call is a reserved word, it must be encased in back ticks:
INSERT INTO calls (wcccanumber, `call`, ...
call is a reserved word in mysql, so if you use it as a column name you need to quote it in backticks:
wcccanumber, `call`, county...
Apart from that you need to switch to PDO / mysqli and prepared statements to fix the potential sql injection problem you have.
call is a reserved word. You'll have to quote it with backticks:
mysql_query("INSERT INTO calls (wcccanumber, `call`, county, id, ...
P.S. For a database problem (especially syntax errors), you don't need to include all of that DOM stuff. how you get the values for a query is pretty much always irrelevant.
Related
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.)
I'm having a problem with my personal server where I'm trying to create a database for the decade old binders I have for the Yu-Gi-Oh! Trading Card Game (haven't played in years). In testing the INSERT INTO, I keep running across a particular problem...
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 ''Magic'(Name, Description, Card_ID, Pack, P_ID, Quantity) VALUES ('Post', 'Post ' at line 1
Now my code outputs properly when I comment out the query function and echo to my webpage, but I keep getting the above mysql_error() message being displayed.
My code snippet is as follows...
if(isset($_SESSION['username'])) {
mysql_connect("localhost", "my_username", "my_password") or die(mysql_error());
mysql_select_db("my_db") or die(mysql_error());
function clean_string($value) {
if(get_magic_quotes_gpc() ) {
$value = stripslashes($value);
}
return mysql_real_escape_string($value);
}
$Show = clean_string($_POST['show']);
$Table = clean_string($_POST['table']);
$Insert_M_T = $_POST['insert_magic_traps'];
$Insert_Monster = $_POST['insert_monster_effect'];
$Insert_Card_Type = clean_string($_POST['I_Type']);
$Insert_Card_Name = clean_string($_POST['I_Card_Name']);
$Insert_Description = clean_string($_POST['I_C_Description']);
$Insert_Card_ID = clean_string($_POST['I_Card_ID']);
$Insert_CardPack = clean_string($_POST['I_C_Pack']);
$Insert_PackID = clean_string($_POST['I_C_P_ID']);
$Insert_Quantity = clean_string($_POST['I_C_Quantity']);
if(isset($Insert_M_T)) {
$sql = "INSERT INTO '$Insert_Card_Type'(Name, Description, Card_ID, Pack, P_ID, Quantity) VALUES ('$Insert_Card_Name', '$Insert_Description', '$Insert_Card_ID', '$Insert_CardPack', '$Insert_PackID', '$Insert_Quantity')";
mysql_query($sql) or die(mysql_error());
echo "<center><h2>Record added to Table: $Insert_Card_Type</h2></center>";
echo "<center><table><tr><th>Name:</th><td>$Insert_Card_Name</td></tr><tr><th>Description:</th><td>$Insert_Description</td></tr><tr><th>Card ID:</th><td>$Insert_Card_ID</td></tr><tr><th>Pack:</th><td>$Insert_CardPack</td></tr><tr><th>Pack ID Number</th><td>$Insert_PackID</td></tr><tr><th>Quantity:</th><td>$Insert_Quantity</td></tr></table></center>";
}
?>
//more html and php code
<?php
} else {
echo "<h1><center><font color=#ff0000 >ACCESS DENIED!!!</font></center></h1>";
echo "<h2><center><a href=index.php >Login Here!</a></center></h2>";
}
?>
Any advice would be helpful. I've tried searching for how to get around this problem, but to no avail. I feel like this is a simple fix, but I'm missing it. Please advise.
Thank you in advance.
~DanceLink
INSERT INTO `$Insert_Card_Type` (Name, Description, Card_ID, Pack, P_ID, Quantity)
VALUES ('$Insert_Card_Name', '$Insert_Description', '$Insert_Card_ID', '$Insert_CardPack', '$Insert_PackID', '$Insert_Quantity')
Backticks around $Insert_Card_Type, not single quotes.
I have tried multiple times to insert into a database. The values contain a single quote - magic quotes are turned off, addslashes() and mysql_real_escape_string() both escape the characters but the script dies without adding to the database. I have also manually escaped but this failed as well. However, even removing the apostrophe, the script still dies.
The error is: Could not insert staff: 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 '11, Hazel, Blonde, Has never missed a day of work, Graduated from Berkley, Serve' at line 2
Anyone see any issues?
<?php
include('header.php');
$amount = 1;
$staffnum = '0101';
$height = array("5'11", "5'4", "6'2","5'5", "6'4");
$eye = array("Blue","Green","Hazel","Brown");
$hair = array("Brown", "Black", "Blonde", "Red");
$about1 = "Has never missed a day of work";
$about2 = "Graduated from Berkley";
$positions = array('Server, Bartender', 'Bartender, Host', 'Sever, Host, Bartender', 'Cocktail Server, Bartender, Server');
$img = "none";
// arrays
$times = 1;
while($times <= 50) {
$staffnum ++;
$heighta = mysql_real_escape_string($height[array_rand($height)]);
$eyea = mysql_real_escape_string($eye[array_rand($eye)]);
$haira = mysql_real_escape_string($hair[array_rand($hair)]);
$positionsa = mysql_real_escape_string($positions[array_rand($positions)]);
$about1 = mysql_real_escape_string($about1);
$about2 = mysql_real_escape_string($about2);
$img = mysql_real_escape_string($img);
$staffnum = mysql_real_escape_string($staffnum);
$insert_staff = "INSERT INTO staff (staffnum, img_link, height, eye, hair, abt1, abt2, titles)
VALUES ($staffnum, $img, $heighta, $eyea, $haira, $about1, $about2, $positionsa)";
$insert_query = mysql_query($insert_staff);
if($insert_query) {
?>
<center>
Member # <?php echo $staffnum; ?> has been added to the database.<br />
<?php
} else {
die('Could not insert staff: ' . mysql_error());
}
$times ++;
}
include('footer.php');
?>
Return To Staff Insert
</center>
You need to put quotes around the string variables you're inserting:
$insert_staff = "INSERT INTO staff (staffnum, img_link, height, eye, hair, abt1, abt2, titles)
VALUES ('$staffnum', '$img', '$heighta', '$eyea', '$haira', '$about1', '$about2', '$positionsa')";
It's a little bit complicated when you want to send so many variables with basic mysql_query.
You should try PDO or mysqli but if you need to use your code, it should be more like
$insert_staff = "INSERT INTO staff (staffnum, img_link, height, eye, hair, abt1, abt2, titles)
VALUES ('".$staffnum."', '".$img."', '".$heighta."', '".$eyea."', '".$haira."', '".$about1."', '".$about2."', '".$positionsa."')";
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."')";
I think this is an escaping issue or something. When I execute the query and populate all variables, everything is peachy and all row is updated properly in the DB.
I looked on StackOverflow to get me rolling with these dynamic/contructed on the fly queries and I'm at the end of my rope.
My stuff looks like this:
$sql="UPDATE users SET ";
if (!empty($fname)) { "fname = '$fname', ";}
if (!empty($lname)) { "lname = '$lname', ";}
if (!empty($location)) { "location = '$location', ";}
if (!empty($url)) { "url = '$url', ";}
"WHERE id = '$id' LIMIT 1";
When I break the query to insert the "IFs" I keep getting 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 '' at line 1
I ECHO'd the query and for some odd reason it's nto complete and the variables are coming in before the query start like so
fname = 'Rob', lname = 'Smith', location = 'Jersey City, NJ', url = 'http://somesite.com', UPDATE users SET 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 '' at line 1
Sorry if I am not clear. I will clarify where needed. I am new at all this. Thank you!
You're not allowed to have a comma after the last thing you SET.
One easy solution is this:
$set = array();
if (!empty($fname)) { $set[] = "fname = '$fname'";}
if (!empty($lname)) { $set[] = "lname = '$lname'";}
if (!empty($location)) { $set[] = "location = '$location'";}
if (!empty($url)) { $set[] = "url = '$url'";}
if(!empty($set)) {
$sql = "UPDATE users SET ";
$sql .= implode(', ', $set)
$sql .= " WHERE id = '$id' LIMIT 1";
}
Oh, and make sure the variables you're shoving in the query are SQL safe; otherwise you've got a SQL injection issue.
Remember in these programming languages, each statement (text ending with a ;) is much like a complete sentence. You need a subject-object-verb for it to make sense. I can't just say
doggy;
I have to say
feed the doggy;
Similarly, I can't just say
"fname = '$fname', "
when I mean "Append this string to the query I started earlier". I have to be explicit:
$sql .= "fname = '$fname', ";
I'm saying "Append this text to $sql". Its a complete sentence.
better to put all your SETs into an array and implode them into a string. That way you can be sure there are no dangling commas. Something like:
if (!empty($fname)) $sets[]="fname = '$fname' ";
if (!empty($lname)) sets[]= "lname = '$lname' ";
if (!empty($location)) sets[]= "location = '$location' ";
if (!empty($url)) sets[]= "url = '$url' ";
$setstring= implode(',',$sets);
if($setstring) {
$query="UPDATE users SET $sets WHERE id = '$id' LIMIT 1";
//run query, etc.
}
Not really a direct answer but for dynamic queries i suggest using PDO. That way you can specify optional parameters more secure, elegant and easier.
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>
If your queries become larger, the way you are doing things now will be pretty complicated to maintain.
echo out your query and take a look at the commas in your SET caluse. Do you have too many? Not enough? I think you'll find that you have one extra comma. You'll probably want to use the implode() function to build up your SET clause. This will insert the appropriate number of commas in the appropriate places.
I see two problems, there is no space before WHERE which means it could turn out "url=http://www.stackoverflow.com"WHERE" and maybe cause a problem.
Also, there is a comma at the end of every SET clause, the last one in the list should not have a comma.