I'm having problems inserting a form $_POST variable to MySQL!
I know it's a single quote problem but simply cannot resolve it.
Code is:
$naziv_db = $_POST["naziv"];
$naziv_db = mysql_real_escape_string($naziv_db);
$query = "INSERT INTO items (title) VALUES ('$naziv_db')";
$stmt = mysql_query($query) or die("MySQL error: " . mysql_error());
If I enter a value containing " it inserts correctly, but if it contains ' then the error appears!
For example if my input is Milky's
error is: MySQL 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
If my input is "Milkys" everything goes well...
I'm new here, so can't post an answer to my own question so i have to edit!
Christian's solution was the right one!
I have changed the code:
$query = "INSERT INTO items (title) VALUES ('$naziv_db')";
to:
$query = 'INSERT INTO `items` (`title`) VALUES ("'.$naziv_db.'")';
and now it accepts both " and ' without error!
Thank you guys, you're the best :D
To avoid this entirely, you'd be best using a prepared statement.
There's a good example in the answer to this question.
Converted for your case, you get:
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("INSERT INTO items (title) VALUES (?)");
$stmt->bind_param('s', $_POST["naziv"]);
$stmt->execute();
$stmt->close();
It's quite impossible to get such an error from your code.
Most likely there is a typo somewhere in it.
May be you're escaping wrong variable or it's another query producing this error
Are you sure you posted the code you actually running? is it exact code or some sketch?
change your mysql_query string to this one
mysql_query($query) or trigger_error(mysql_error()." ".$sql);
and paste it's output please.
or, even change whole code:
ini_set('display_errors',1);
error_reporting(E_ALL);
$naziv_db = $_POST["naziv"];
$naziv_db = mysql_real_escape_string($naziv_db);
$query = "INSERT INTO items (title) VALUES ('$naziv_db')";
var_dump($_POST["naziv"]);
echo "<br>\n";
var_dump($naziv_db);
echo "<br>\n";
var_dump($query);
echo "<br>\n";
mysql_query($query) or trigger_error(mysql_error()." ".$sql);
this is called "debugging" and usually helps.
Try addslashes - it's made for parsing strings into database-friendly content.
Related
php/mysql
I keep getting 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 '1' at line 1".
I'm trying hard to make this query to happen. It works, it inserts into the mysql database but this error appears every time. I've tried to use everything in the same line, changed double quotes to single quotes, removed all the whitespaces inserting everything in the samen line, changing the way I pass the variables({$variable} to '.$variable.') and everything else. I've seen a couple of stackoverflow questions related to this but with different solutions.
I know that we can't pass '' in a numeric fields.
I think I'm out of options now. Need help!
This error keeps showing but the data is correctly inserted in my table
here is the code:
$user_id = get_current_user_id();
$prescription_name = $_POST['prescription_name'];
$date_created = date('Y-m-d');
$last_updated = date('Y-m-d');
$right_eye_sphere = $_POST['right_eye_sphere'];
$left_eye_sphere = $_POST['left_eye_sphere'];
$right_eye_cylinder = $_POST['right_eye_cylinder'];
$left_eye_cylinder = $_POST['left_eye_cylinder'];
$right_eye_axis = $_POST['right_eye_axis'];
$left_eye_axis = $_POST['left_eye_axis'];
$pd = $_POST['pd'];
$date_of_birth = $_POST['date_of_birth'];
$file_path = $_POST['file_path'];
$add_query = "INSERT INTO wew_prescription (
prescription_id,
user_id,
prescription_name,
date_created,
last_updated,
right_eye_sphere,
left_eye_sphere,
right_eye_cylinder,
left_eye_cylinder,
right_eye_axis,
left_eye_axis,
pd,
date_of_birth,
file_path
) Values (
NULL,
{$user_id},
'{$prescription_name}',
'{$date_created}',
'{$last_updated}',
'{$right_eye_sphere}',
'{$left_eye_sphere}',
'{$right_eye_cylinder}',
'{$left_eye_cylinder}',
'{$right_eye_axis}',
'{$left_eye_axis}',
'{$pd}',
'{$date_of_birth}',
'{$file_path}'
)";
$sql = $dbCon->query($add_query);
if (!mysqli_query($dbCon,$sql)){
die('Error: ' . mysqli_error($dbCon));
}else{
mysqli_query($dbCon,$sql);
echo "dados atualizados!";
}
The error is coming from this line:
if (!mysqli_query($dbCon,$sql)){
$sql contains the result of
$dbCon->query($add_query);
Since that query was successful, $sql contains TRUE. mysqli_query() requires the second argument to be a string, so TRUE becomes "1", so you're effectively doing:
if (!mysqli_query($dbCon, "1")) {
That's not a valid query, so you get an error.
I think what you really meant to do was:
if (!$sql) {
die('Error: ' . $dbCon->error);
} else {
echo "dados atualizados!";
}
You don't need to keep calling mysqli_query() repeatedly.
You should also learn to code using prepared statements instead of substituting variables into the query, to prevent SQL injection.
I am receiving the above error when trying to insert into a SQL Server DB. The error is line 25, which is the $logQuery line but I am pretty sure that it has something to do with the insert statement, which is line 24. Here is the insert statement:
$logInsert = "INSERT into log (id, title, description, dateTime) VALUES ('', 'In', 'ADMIN: Todd Thelin logged into site.', GETDATE())";
And here is the query:
$logQuery = sqlsrv_query($conn, $logInsert) or die("Could not add to log: " . sqlsrv_errors());
How do I fix this error? I have tried multiple things but none of them are working. Thank you
I believe sqlsrv_errors() is returning an array. That makes the die function to fail.
Old thread but it helped me realize the following solution for this... wrapping print_r() around the sqlsrv_errors() function:
$logQuery = sqlsrv_query($conn, $logInsert) or die("Could not add to log: " . print_r(sqlsrv_errors()));
I am using the following script to enter data into my database from a form. I have echo'd each of the values declared at the beginning and they are all coming across just fine.
include("connectmysqli.php");
echo '<link rel="stylesheet" href="http://towerroadacademy.co.uk/templates/rt_reflex_j16/css/template.css">';
if (isset($_GET['questionnaireID'])) {$questionnaireID = $_GET['questionnaireID'];}else {$questionnaireID = '';}
if (isset($_POST['newquestionnumber'])) {$questionnumber = $_POST['newquestionnumber'];}
if (isset($_POST['questionID'])) {$questionID = $_POST['questionID'];}else {$questionID = '';}
if (isset($_POST['question'])) {$question = $_POST['question'];}else {$question = '';}
if (isset($_POST['lowerlabel'])) {$lowerlabel = $_POST['lowerlabel'];}else {$lowerlabel = '';}
if (isset($_POST['middlelabel'])) {$middlelabel = $_POST['middlelabel'];}else {$middlelabel = '';}
if (isset($_POST['upperlabel'])) {$upperlabel = $_POST['upperlabel'];}else {$upperlabel = '';}
$stmt = $db->prepare("INSERT INTO `QuestionnaireQuestions` (`questionnaireID`, `questionnumber`, `questionID`, `question`, `lowerlabel`, `middlelabel`, `upperlabel`) VALUES ($questionnaireID', '$questionnumber', '$questionID', '$question', '$lowerlabel', '$middlelabel', '$upperlabel') WHERE questionnaireID='$questionnaireID';");
if (!$stmt) trigger_error($db->error);
$stmt->execute();
I keep getting the following error though and cant seem to trace what is causing it.
Notice: 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 '', '3', '1947679104', 'questonofngdfngodfngo', 'lower', 'midddle', 'upper') WHER' at line 1 in /home2/towerroa/public_html/questionnaires/addanotherquestionsubmit.php on line 16 Fatal error: Call to a member function execute() on a non-object in /home2/towerroa/public_html/questionnaires/addanotherquestionsubmit.php on line 17
The table QuestionnaireQuestions looks like this :
id questionnaireID questionnumber questionID question lowerlabel middlelabel upperlabel
You're missing a quote on $questionnaireID:
INSERT INTO `QuestionnaireQuestions` (`questionnaireID`, `questionnumber`, `questionID`, `question`, `lowerlabel`, `middlelabel`, `upperlabel`) VALUES ('$questionnaireID', '$questionnumber', '$questionID', '$question', '$lowerlabel', '$middlelabel', '$upperlabel')
Also remove the WHERE clause.
UPDATE statements can use the WHERE statement to update existing database records based upon a condition. Granted INSERT SELECT statements can contain a WHERE, INSERT statements by themselves do not.
INSERT will not work with the WHERE condition,if only you want to UPDATE the row then you can use WHERE condition and replace this
VALUES ($questionnaireID',......
with
VALUES ('$questionnaireID',
You have missed a single quote and remove ';' from the end also.Now the query will be
$stmt = $db->prepare("INSERT INTO `QuestionnaireQuestions` (`questionnaireID`,
`questionnumber`, `questionID`, `question`, `lowerlabel`,
`middlelabel`, `upperlabel`) VALUES ('$questionnaireID',
'$questionnumber', '$questionID', '$question', '$lowerlabel',
'$middlelabel', '$upperlabel')");
But I must appreciate that you are using PDO statements instead of mysql_* deprecated functions
($questionnaireID'
should be
('$questionnaireID'
but you should really try working with prepared statements
I'm trying to pass a MySQL query with variables from flex to MySQL using php.
This is the Query in Flex. Everything appears to be correct.
mysqlQuery("INSERT INTO poc_note_test (first_name,last_name) VALUES ("+firstName+"," +lastName+")");
When the query is passed to my server via http to be processed by PHP it returns 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 'Test_Value )' at line 1
From what I can see it is trying to include the final ")" as part of the value. I for the life of me cannot see how to stop this from happening.
Here is the php that is being used to process the query where it errors out.
$sql = $_REQUEST['sql'];
$result = mysql_query($sql);
$err = mysql_error();
$cols_count = mysql_num_fields($result) or error_log('Invalid query: ' .mysql_error());
Any help will be much appreciated
This is the function passing the query. Maybe the issue is here?
public function mysqlQuery(sql:String,fid:String):void {
var http:HTTPService = new HTTPService;
var parm:Object = new Object;
parm.sql = sql;
parm.private_key = private_key;
parm.fas_db = mysql_db;
http.url = mysql_url+"?irand="+Math.random();
http.showBusyCursor = true;
http.request = sql;
http.addEventListener(ResultEvent.RESULT, mysqlResult);
http.addEventListener(FaultEvent.FAULT, mysqlFault);
http.method = "POST";
sqlToken = http.send(parm);
sqlToken.param = fid;
}
Change this
mysqlQuery("INSERT INTO poc_note_test (first_name,last_name) VALUES ("+firstName+"," +lastName+")");
to
mysqlQuery("INSERT INTO poc_note_test (first_name,last_name) VALUES ('"+firstName+"','" +lastName+"')");
put ' around values
For removing \
$result = mysql_query(stripslashes($sql));
Changed into
mysqlQuery("INSERT INTO poc_note_test (first_name,last_name) VALUES ("+firstName+"," +lastName+")");
to
mysqlQuery("INSERT INTO poc_note_test (first_name,last_name) VALUES ('"+firstName+"','" +lastName+"')");
IN sql , the string character are quoted in single quotes/double quotes.
Dreamweaver is reporting an error in the 3rd line of the following code:
if (isset($_POST['sitename']))
{
$query = "INSERT INTO dllist (name, url, pr) VALUES ( "$_REQUEST['sitename'], $_REQUEST['siteurl'], $_REQUEST['pagerank']" )";
$result = mysql_query($query)
or die("Query Failed".mysql_error());
echo "<br />Website Has been added<br />";
}
Also, when running the code in my browser the following error is reported
Parse error: syntax error, unexpected '$_REQUEST' (T_VARIABLE)
Can anybody tell me where the mistake is? I shall really be grateful.
The commas (and the fact your missing the containers around your values (e.g. single quotes)), it should be:
$query = "INSERT INTO dllist (name, url, pr) VALUES ('".$_REQUEST['sitename']."', '".$_REQUEST['siteurl']."', '".$_REQUEST['pagerank']."')";
Although this is still bad practice, and it has no SQL Injection protection.
You need to concatenate the string. Change VALUES (" to VALUES (" .
the values you put in insert query need to be single quoted individually like this:
$query = "INSERT INTO dllist (name, url, pr) VALUES ( '$_REQUEST['sitename']', '$_REQUEST['siteurl']', '$_REQUEST['pagerank']' )";