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."')";
Related
I am inserting data from a excel sheet but i receive error and it looks like it is breaking because the value contain a space character in between. As far as i remember space characters allowed in VARCHAR(200)
This is the code i am using
//CREATE SQL QUERY FOR INSERTING DATA IN DATABASE
$sql = "INSERT INTO ".$month."_".$year."(";
foreach($sheetData[1] as $columnName){
$sql .= preg_replace('#[ ]#', '_',$columnName). ",";
}
$sql = rtrim($sql, ',');//REMOVES COMMA FROM END OF THE STRING
$sql .= ")";
//
$sql .= " VALUES((";
for($i=2;$i < count($sheetData);$i++){
foreach($sheetData[$i] as $columnName){
$sql .= $columnName.",";
}
$sql = rtrim($sql,',');//
$sql .= "),";
}
$sql = rtrim($sql,',');//
$sql .= ")";
echo $sql;
$query = mysqli_query($conn,$sql) or die(mysqli_error($conn));
After loops this is how my SQL QUERY look
INSERT INTO December_2015(S_No,Zone,State,City2,VM_Town,Distibutor_Code,Distributor_Name,Dealer_Code,Dealer_Name,Category,Address,Location,Contact,Mobile_No,Visit_1,Visit_2,Visit_3,Visit_4,Visit_5,Visit_6) VALUES( (1,South,Telanagana,Hyderabad,Y,1006704,Sai Santhoshi Enterprises,TG000999,Sree Laxmi Mobiles,A,F4,anthem Arcade,gujarathi Galli,koti ,Koti,Rajesh,8790575680,7-Nov,18-Nov,28-Nov))
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 'Santhoshi Enterprises,TG000999,Sree Laxmi Mobiles,A,F4,anthem Arcade,gujarathi G' at line 1
It says near 'Santhoshi Enterprises ... ' before that there is a space character
You have two "(" instead of one after "VALUES"
Akash,
Didn't you asked a question just a while ago regarding same/similar code with a different error you got, here at: How to loop inside a variable ?!
By the looks of it in general you write messy code, and you are having trouble reading/understanding the error messages. So I'm gonna guess you are new at this.
Here are some good reads for you:
Top 15+ Best Practices for Writing Super Readable Code
PHP the right way
When all said and done, here is your code broken down into more readable segments:
// prepare dummy data
$month = date('M');
$year = date('Y');
$sheetData = array(
array('data00', 'data01')
,array('col1', 'col2', 'col3', 'col4', 'col5', 'col6')
,array('data20', "data21")
,array('data30', 'data31')
,array('data40', 'data41')
);
// prepare vars
$tableName = "{$month}_{$year}";
$dataCount = count($sheetData);
// prepare columns
$columnsSQL = "";
foreach ($sheetData[1] as $columnName) {
// wrap with ` ticks
$columnsSQL .= '`'. preg_replace('#[ ]#', '_', $columnName).'`'.',';
}
$columnsSQL = rtrim($columnsSQL, ',');
// prepare values
$valuesSQL = "";
for ($i=2;$i < $dataCount;$i++) {
foreach($sheetData[$i] as $columnValue){
$valuesSQL .= "'{$columnValue}', ";
}
}
$valuesSQL = rtrim($valuesSQL, ', ');
$SQL = "
INSERT INTO {$tableName}( {$columnsSQL} )
VALUES ( {$valuesSQL} )";
At the end you end up with something like this:
INSERT INTO Nov_2015( `col1`,`col2`,`col3`,`col4`,`col5`,`col6` )
VALUES ( 'data20', 'data21', 'data30', 'data31', 'data40', 'data41' )
Additional note and tips:
Considering that you said you are reading data from excel sheet... Never trust input data without some tests/checks/validation. Not just because of security but stability and in general you don't want things breaking.
Those excel tables could be manually made which automatically means its prone for human error, so you can't be always 100% sure what are you gonna get.
Consider using PDO and prepared statements (security reasons, but also good practice)
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.
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.
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.