MYSQL PHP - You have an error in your SQL syntax - php

why i always get error in hostgator when try to update this ga field in database, error happen when insert this code in textarea
_gaq.push(['_setCustomVar',1, 'Status', 'Logged In']);
_gaq.push(['_trackEvent', 'Custom', 'PageLoad', 'Setting Logged In State',0,true]);
<textarea name="ga"></textarea>
$name = $_POST['name'];
$ga = trim($_POST['ga']);
$req = "UPDATE `con` SET `name` = '".$name."', `ga` = '".$ga."'");
if (mysqli_query($con, $req)) {
echo "success"
}
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 '_setCustomVar',1, 'Status', 'Logged In']);
_gaq.push(['_trackEvent', 'Custom', ' at line 1
if i remove ga = '".$ga."' my database update but if add this code it give error i have hostgator and it work good in localhost
type of ga in database is text.

Prepared statements are the one stop solution for this. Your code is supposed to be:
$name = trim($_POST['name']);
$ga = trim($_POST['ga']);
$some_value = 'some_value'; //This is just the imaginary value for demonstration
$req = "UPDATE `con` SET `name` = ?, `ga` = ? WHERE column_name = ?";
$stmt = $mysqli->prepare($req);
$stmt->bind_param('sss', $name, $ga, $some_value);
$stmt->execute();
You always want to use WHERE with UPDATE query. If you don't use WHERE clause, the changes will be applied to all records. I suppose you are aware of SQL injection, the notorious attack!
An alternative which can be used to fix the issue with your code is mysqli_real_escape_string().
For example,
$name = mysqli_real_escape_string($con, trim($_POST['name']));
$ga = mysqli_real_escape_string($con, trim($_POST['ga']));
But always use prepared statements as I've shown above.

Related

Inserting check box data in mysql using php

I am creating a form where a user tick on the checkbox then 1 will be stored in that column on MySQL table. If the user does not tick then 0 will be stored on that field in the database. One checkbox for one column. My HTML code is :
Type ;<label class="checkbox-inline"><input type="checkbox" name="mentor" value="1" >Mentor</label>
<label class="checkbox-inline"><input type="checkbox" name="core" value="1" >Core</label>
and my PHP code is
$name = mysqli_real_escape_string($DBcon, $_POST['name']);
$mentor;
if (isset ($_POST['mentor']) == "1")
{
$mentor = 1;
}
else
{
$mentor = 0;
}
$core;
if (isset ($_POST['core']) == "1")
{
$core =1;
}
else
{
$core =0;
}
$insert = $DBcon->query("INSERT into contributor(name,mentor,core) VALUES('$name','$mentor','$core')");
But I am getting "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 '????\"Exif\0\0MM\0*\0\0\0\0\0\0\0\0\0?\0\0\0\0\0\0?\0\0\0\0\0\0\' at line 1"
this error when I press submit button
PHP uses single quotes to mean literals. That is, the $varname won't be interpreted to mean 0, it will mean $varname. Remove the single quotes and it should work.
"INSERT into contributor(name,mentor,core) VALUES($name,$mentor,$core)"
or
'INSERT into contributor(name,mentor,core) VALUES('.$name.','.$mentor.','.$core.')'
If this is for work, please read up on PHP PDO and the security it adds.
# as #War10ck mentioned, you're mixing Procedural-style with object oriented
$name = $DBCon->real_escape_string($_POST['name']);
# You were comparing a boolean (isset) with "1". Since it's a checkbox, you an do this (or $_POST['mentor'] == "1" since that's your value on the form..)
$mentor = isset($_POST['mentor']) ? 1 : 0;
$core = isset($_POST['core']) ? 1 : 0;
# remove single quotes from your $paramaters
$insert = $DBcon->query("INSERT into contributor(name,mentor,core) VALUES($name, $mentor, $core)");
Note you should use PDO prepared statements as others have mentioned
$stmt = $DBcon->prepare("INSERT INTO contributor(name, mentor, core) VALUES(?,?,?)");
$stmt->bind_param('sssd', $name, $mentor, $core);
$insert = $stmt->execute();
You appear to be mixing procedural and object-oriented mysqli_* statements in your code. You should choose one or the other. Change your line here:
mysqli_real_escape_string($DBcon, $_POST['name']);
to this instead:
$DBCon->real_escape_string($_POST['name']);
In addition, you will also want to remove the nested single quotes in your query statement:
$insert = $DBcon->query("INSERT into contributor(name,mentor,core) VALUES($name,$mentor,$core)");
SECURITY IMPLICATIONS:
I cannot go without saying (and without echoing the comments above), that you are leaving yourself open to SQL Injection attacks using this method. To ensure that you are protected, you should consider using the prepared statements offered by both the mysqli_* and PDO_* extensions.
Consider using the following safer alternative instead of the code you used above:
$DBCon = new \PDO('{dsn}', '{user}', '{pass}', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => FALSE
]);
$mentor = (isset($_POST['mentor']) AND intval($_POST['mentor']) === 1) ? 1 : 0;
$core = (isset($_POST['core']) AND intval($_POST['core']) === 1) ? 1 : 0;
try {
$stmt = $DBCon->prepare("INSERT INTO contributor(name,mentor,core) VALUES (:name,:mentor,:core)");
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':mentor', $mentor, PDO::PARAM_INT);
$stmt->bindParam(':core', $core, PDO::PARAM_INT);
$stmt->execute();
/* Cleanup (if you are finished interacting with the database) */
$stmt = NULL;
$DBCon = NULL;
} catch (\PDOException $e) {
/* Handle Error Here */
}

keep getting a syntax error (php / mysql)

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.

A Possible Bug with PDO's bindParam, bindValue and foreach

I have been getting an error with this code.
$Database = new Database('localhost','root','password','Db');
$Statement = $Database->prepare("INSERT INTO User VALUES(:ID,:FirstName,:MiddleName:LastName,:RegisteredDate")
$Array_Bind = array(
'ID'=>$ID,
'FirstName'=>$FirstName,
'MIddeName'=>$MiddleName,
'LastName'=>$LastName
'RegisteredDate'=>$Date
)
foreach($Array_Bind AS $Key=>$value){
$Statement->bindParam(':' .$Key, $value)
}
if($Statement->execute()){
echo 'Successfully inserted into the database';
}else{
echo 'could not insert into database';
};
The following have been noted IF the $ID (PrimaryKey) is NOT by DEFAULT an AUTO-INCREMENTING value in the MySQL Database.
ALL Fields except DATETIME Fields gets the value of the last element in the array when inserted into the database.
i.e.
ID = $LastName
FirstName = $LastName
MiddleName = $LastName
LastName = $LastName
RegisteredDate = $RegisteredDate
The same error is outputted when bindValue is used.
So I ended up using
if($Statement->execute($Array_Bind)){
echo 'Successfully inserted into the database';
}else{
echo 'could not insert into database';
};
QUESTIONS
It is recommended to use execute($array_Bind) assuming all data have been sanitize as against using bindParam or bindValue in this scenario?
If Not is there a way to use bindParam or bindValue and arrays?
Is this a bug or wrong coding architecture.
I noticed you had a typo in the placeholder name. Don't know if this will sort the problem
$Statement = $Database->prepare("INSERT INTO User VALUES(:ID,:FirstName,:MiddleName:LastName,:RegisteredDate")
$Array_Bind = array(
'ID'=>$ID,
'FirstName'=>$FirstName,
'MIddeName'=>$MiddleName,
'LastName'=>$LastName
'RegisteredDate'=>$Date
)
You use a placeholder MIddeName but in your query you use MiddleName
Change this
'MIddeName'=>$MiddleName,
to this
'MiddleName'=>$MiddleName,
You need to check your premises. Then double check. Then check documentation.
with bindParam it is not a bug but essential feature.
with bindValue it never happen
of course passing array into execute() is preferred, due to overall sanity and amount of code compared to other methods.

PDO prepared statement update not working

am new to prepared statements and PDO. I have a script with two prepared statements, the insert statement works fine, yet the update does not. It returns no errors and displays the success message, yet it doesn't update the database.
Here is the code that doesn't work. Any help wouild be much appreciated. Thanks
$queryString="UPDATE team_directory SET team_name=':team_name',
aka=':aka',
website=':website',
main_contact=':main_contact',
phone=':phone',
email=':email',
other=':other',
np1=':np1',
np2=':np2',
np3=':np3',
np4=':np4',
np5=':np5',
np6=':np6',
np7=':np7',
np8=':np8',
np9=':np9',
np10=':np10',
np11=':np11',
np12=':np12'
where team_id=':team_id'";
$query=$database->prepare($queryString);
$query->execute(array(':team_name'=>$team_name,
':aka'=>$aka,
':website'=>$website,
':main_contact'=>$main_contact,
':phone'=>$phone,
':email'=>$email,
':other'=>$other,
':np1'=>$np1,
':np2'=>$np2,
':np3'=>$np3,
':np4'=>$np4,
':np5'=>$np5,
':np6'=>$np6,
':np7'=>$np7,
':np8'=>$np8,
':np9'=>$np9,
':np10'=>$np10,
':np11'=>$np11,
':np12'=>$np12,
':team_id'=>$team_id));
if ($query->errorCode()==0) {
echo "<p>Team amended successfully, Amend Another </p>
<p>Team Directory</p>
<p>Admin Homepage</p>";
}
else {
$errors=$query->errorInfo();
echo ($errors[2]);
}
Simply take the placeholders (your to-be-used prepared statement markers for variables) out of those evil quotes:
$queryString="UPDATE team_directory SET team_name = :team_name,
aka = :aka,
website = :website,
main_contact = :main_contact,
phone = :phone,
email = :email,
other = :other,
np1 = :np1,
np2 = :np2,
np3 = :np3,
np4 = :np4,
np5 = :np5,
np6 = :np6,
np7 = :np7,
np8 = :np8,
np9 = :np9,
np10 = :np10,
np11 = :np11,
np12 = :np12
where team_id = :team_id";

Syntax error at update query where clause mysql

if(isset($_POST['Update'])) {
$placename = $_POST['placename'];
$description = trim(addslashes($_POST['description']));
$hotel = $_POST['hotel'];
$transport = $_POST['transport'];
$map = $_POST['map'];
$sqlp = "UPDATE places SET placename = $placename, description = $description, hotel = $hotel, transport = $transport, map = $map WHERE place_id = ". $sPlace['place_id'];
connection();
if(mysql_query($sqlp)) {
echo "Successfully Updated";
} else {
echo mysql_error();
}
}
Error Message is following-
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 '
map = map WHERE place_id = 54' at line 1
You error in that code is that you don't add quotes around variables, it should be like this:
$query = "UPDATE `table` SET `name`='".mysqli_real_escape_string($_POST['name'])."' WHERE `id`=1";
But please try to use PDO with transaction as you will be able to debug any errors and you don't have to worry about SQL Injection.
Try this: (you will see errors, and if it's not ok, it will rollback)
$db = new PDO('mysql:host=localhost;dbname=databaseName', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false));
$placename = $_POST['placename'];
$description = trim(addslashes($_POST['description']));
$hotel = $_POST['hotel'];
$transport = $_POST['transport'];
$map = $_POST['map'];
try {
$db->beginTransaction();
$stmt = $db->prepare("UPDATE `places` SET `placename`=:placename, `description`=:description, `hotel`=:hotel, `transport`=:transport, `map`=:map WHERE `place_id`=:place_id");
$stmt->execute(array(':placename' => $placename, ':description' => $description, ':hotel' => $hotel, ':transport' => $transport, ':map' => $map, ':place_id' => $sPlace['place_id']));
$db->commit();
} catch(PDOException $ex) {
$db->rollBack();
echo $ex->getMessage();
}
You have an error in your SQL syntax ... 'map = map WHERE place_id = 54' at line 1
map = map <-- is invalid. the right-side should be an sql value (quoted string, number, etc). Perhaps map = 'map' (quote the value) is the intended result?
The problem you are seeing has come about because none of your string literals have been quoted, so the comma in the value of $transport is being evaluated as a separator between SQL SET clauses and so gives rise to the syntax error that you witness.
You should quote your string literals—or better yet, use parameterised statements so that your variables do not get evaluated for SQL at all (which avoids all forms of SQL injection attack).

Categories