I've tried this query with both commas and "AND" statements as pictured below. I get a syntax error
Something went wrong.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 'are available 24/7 by phone and email to answer any questions and to assist you ' at line 1
every time I try this query:
$sql = mysql_query("UPDATE general
SET bookabandheading = $_POST[bookabandheading
AND bookaband = $_POST[bookaband]
AND contactus = $_POST[contactus]
AND aboutuslisten = $_POST[aboutuslisten]
AND contactusheading = $_POST[contactusheading]
AND nightclubsheading = $_POST[nightclubsheading]
AND acousticheading = $_POST[acousticheading]
AND schoolsheading = $_POST[schoolsheading]
AND privateheading = $_POST[privateheading]
AND concertsheading = $_POST[concertsheading]
AND festivalsheading = $_POST[festivalsheading]
AND submissions = $_POST[submissions]
AND interns = $_POST[interns]
AND managementbio = $_POST[managementbio]
AND latestnews = $_POST[latestnews]
AND artistofthemonth = $_POST[artistofthemonth]
AND artistofthemonthphoto = $_POST[artistofthemonthphoto]
AND artistofthemonthid = $_POST[artistofthemonthid]
AND listentoourartists = $_POST[listentoourartists]
AND musicianswanted = $_POST[musicianswanted]
AND aboutus = $_POST[aboutus]
AND bshowcases = $_POST[bshowcases]
AND bandavails = $_POST[bandavails]");
The query worked in a different database on another VPS, but I just migrated servers and it no longer works. Any help is greatly appeciated!
While the main problem is that you missed the closing bracket after bookamandheading, still I would like to advise you to refactor this request for example like this:
$keys = array("bookabandheading", "bookaband", "contactus", "aboutuslisten",
"contactusheading", "nightclubsheading", "acousticheading",
"schoolsheading", "privateheading", "concertsheading",
"festivalsheading", "submissions", "interns", "managementbio",
"latestnews", "artistofthemonth", "artistofthemonthphoto",
"artistofthemonthid", "listentoourartists", "musicianswanted",
"aboutus", "bshowcases", "bandavails");
$set = array();
foreach ($keys as $key) {
$set[] = sprintf(" %s = '%s' ", $key, mysql_escape_string($_POST[$key]));
}
$sql = mysql_query("UPDATE general SET " . implode(", ", $set));
It is much easier to maintain and also a bit more secure by escaping the input.
Update: add where statement example
$where = array();
$where[] = sprintf(" some_string = '%s' ", mysql_escape_string($some_string));
$where[] = sprintf(" some_integer = %d ", $some_integer);
$where = " WHERE " . implode(" AND ", $where);
$sql = mysql_query("UPDATE general SET " . implode(", ", $set) . " " . $where);
I see 3 things wrong with this:
Raw POST data in your query - at the very least user mysql_real_escape_string
The parameters look like strings so should have quotes around them
There's no WHERE option, so you'll update every row in that table
You have a few errors:
Syntax error. Change
$_POST[bookabandheading to $_POST[bookabandheading]
This is also incredibly prone to SQL injections. You should be using mysqli, but if you are set on mysql (which is deprecated as of 5.5.0), you should escape each $_POST variable using mysql_real_escape_string().
Each $_POST variable needs to bee parameterized using quotes a well. So, an example:
$_POST['bookabandheading'] (do this for all $_POST variables)
$_POST[bookabandheading
change to
$_POST[bookabandheading]
Related
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 5 years ago.
I have the MySQL table that has filename and description fields.
Then, I wrote this code to do LIKE search.
However my poor code cannot conduct what I want to do.
Error message says
Syntax error or access violation.
PHP 7.0 / MySQL 5.0.95 is my server's.
$keywords = str_replace( "\xc2\xa0", " ", $keywords );
$keywords = preg_replace("/[\s]+/", " ", trim($keywords));
$keywordsarray = array_unique(explode(' ', $keywords));
$sql1 = "SELECT * FROM file_table WHERE ";
$sql2 = array();
$key = array();
foreach ($keywordsarray as $word) {
$sql2[] = " (filename LIKE ? OR describe LIKE ? )";
$key[] = '%'.$word.'%';
$key[] = '%'.$word.'%';
}
$builtsql = $sql1.implode(' AND ', $sql2);
$query = $db->prepare($builtsql);
$query->execute($key);
Could you give me good ideas? Thanks.
The issue is caused by not escaping the reserved word describe in your query.
You should be able to resolve the Syntax error issue by wrapping the column name(s) in identifier quotes (backtick).
$sql2[] = " (`filename` LIKE ? OR `describe` LIKE ? )";
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)
hey guys im trying to update my database using php ang ajax, but assuming that the textbox are dynamic thats why im trying to update the database using multiple updates with one click of a button but my fire bug says that "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 '= '100' WHERE student_id = '33' AND subject_id = '2' AND school_id = '1' AND adv' at line 1 " im not pretty sure with my code because im just experimenting on how to do it in ajax with php.
PHP:
session_start();
$school_id = $_SESSION['school_id'];
$faculty_id = $_SESSION['user_id_fac'];
$subject_id = $_POST['subject_id'];
$year_grade_level = $_POST['year_level'];
$subject_handeler_id = $_POST['subject_handler_id'];
$student_grades_boy = $_POST['student_grades_boy'];
$student_grades_girl = $_POST['student_grades_girl'];
$update_grades_boys = "UPDATE registrar_grade_archive SET";
//SET status = '0' WHERE subject_id = '$subject_id'"
$vaues_girl = array();
$values_boy = array();
foreach ($student_grades_boy as $key=>$data) {
$student_id_B= $data['studnt_B_id'];
$grade_B = $data['studnt_grade_B'];
$values_boy[$key] = 'grade = \''.$grade_B.'\' WHERE student_id = \''.$student_id_B.'\' AND subject_id = \''.$subject_id.'\' AND school_id = \''.$school_id.'\' AND advisor_faculty_id = \''.$faculty_id.'\' AND subject_handler_id = \''.$subject_handeler_id.'\' ' ;
}
$values_boy = implode(', ', $values_boy);
$ready_edit_grades_boy = $update_grades_boys . $values_boy;
$save_grades_boy = mysql_query($ready_edit_grades_boy) or die(mysql_error());
please help guys. thanks in advance
Some problems here:
if $student_grades_boy contains more than 1 item, your sql will have multiple WHERE statements (you can only have 1);
you need a space between SET and the column name;
you have a serious sql injection problem;
you should switch to PDO or mysqli as the mysql_ functions are deprecated.
It appears you have no space between SET and grade.
Adding a space here should do the trick:
$update_grades_boys = "UPDATE registrar_grade_archive SET ";
If this doesn't do it, it would help tremendously if you could post the result of echo $ready_edit_grades_boy; and update your question.
try
$update_grades_boys = "UPDATE registrar_grade_archive SET ";
One space is needed after SET..
You are not escaping vars, so it could be some ' or " in your values.
http://php.net/manual/en/mysqli.real-escape-string.php
$tagList = get_the_tag_list('','---','');
$totaltags = explode('---',$tagList);
foreach ($alltags AS $eachtag)
{
$thistag = GetBetween($eachtag,'/tag/','/');
$SQL = "SELECT * FROM table WHERE thetag = '$eachtag'"
$result = mysql_query($SQL, $link) or die(mysql_error());
if(mysql_affected_rows()>0)
{
echo $thistag;
}
}
This is my working code. It works, but I really don't like having the SQL command in the foreach. I assumed it wouldn't be an issue since there's no more than 8 tags on any given page. Is there a more efficient way to code this? (i.e. optimize for 1 mysql command or have less code)
This is my working code. It works, but I really don't like having the SQL command in the foreach. I assumed it wouldn't be an issue since there's no more than 8 tags on any given page. Is there a more efficient way to code this? (i.e. optimize for 1 mysql command or have less code)
Quite simple really:
<?php
// build quotes around the tags, this specific syntax is PHP 5.3+
$alltags = array_map( $alltags, function( $value ) {
return "'" . mysql_real_escape_string( $value ) . "'";
});
$query = 'SELECT * FROM table WHERE thetag IN ( %s );';
$sql = sprintf( $query, implode( ', ', $alltags ) );
echo $sql;
Take a look at the FIND_IN_SET function.
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.