Ucwords/SQL error with special characters - php

I have a table with all the cities in my country, but they are in uppercase. Im trying to convert the first letter to uppercase and the rest to lower case.
Some of them have the single quote accent (Example: Sao Martinho D'oeste) and they are the only ones that give me an error when i try to update the table after converting them.
$cidadeNome = strtolower($cidade['desc_cidade']);
$cidadeNome = ucwords($cidadeNome);
$sql = "UPDATE cidades SET desc_cidade = '".$cidadeNome."' WHERE cidade_id = ".$cidade['cidade_id']."";
$atualizado = $db->query($sql);
if (!$atualizado)
{
echo "Erro (" . $db->errno . ") " . $db->error . "\n";
$db->close();
exit;
}
My code is very simple. The error i get is
Erro em (1064) 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 'oeste' WHERE cidade_id = 88382' at line 1
My code work for every city, unless it has an single quote.

Related

Query working in phpMyAdmin but not php - You have an error in your SQL syntax;

I have a simple query which works in phpMyAdmin but not via mysqli_query:
$update_sql = "
UPDATE db SET db.period = ('January-2017') WHERE db.column between '2016-12-16' and '2017/01/29';
UPDATE db SET db.period = ('February-2017') WHERE db.column between '2017-01-30' and '2017/02/26';
";
echo '<p>'.$update_sql.'</p>';
$result_mysqli_query=mysqli_query($link,$update_sql);
if(! $result_mysqli_query) {
die("SQL Error: " . mysqli_error($link));
}
The output from mysqli_error() gives:
SQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE db SET db.period' at line 2
Ive tried surrounding the field names with '`', copying the output from the echo statement to PHP to see if the generated string works the same, but still no joy.
There are more than one issues like, what are you trying to update here:
db.period = ('January-2017')
what is the datatype of db.period here and the condition:
WHERE db.column between '2016-12-16' and '2017/01/29';
here you are using two different date formats. Resolve these issues and than run the query again.
I think your second UPDATE line contains a redundant semicolon.
Try the simple test - does it work for a single UPDATE line?
$update_sql = "UPDATE db SET db.period = ('February-2017') WHERE db.column between '2017-01-30' and '2017/02/26'";
echo '<p>'.$update_sql.'</p>';
$result_mysqli_query=mysqli_query($link,$update_sql);
if(! $result_mysqli_query) {
die("SQL Error: " . mysqli_error($link));
}
mysqli_multi_query() not mysqli_query()
For anyone else that comes accross this, as per #Lawrence Cherone's comment, it was actually something simple - using mysqli_multi_query() instead of mysqli_query()
$update_sql = "
UPDATE db SET db.period = ('January-2017') WHERE db.column between '2016-12-16' and '2017/01/29';
UPDATE db SET db.period = ('February-2017') WHERE db.column between '2017-01-30' and '2017/02/26';
";
echo '<p>'.$update_sql.'</p>';
$result_mysqli_query=mysqli_multi_query($link,$update_sql);
if(! $result_mysqli_query) {
die("SQL Error: " . mysqli_error($link));
}

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.

PHP MYSQL SELECT query hanging on negative value or syntax in WHERE clause [duplicate]

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 8 years ago.
I have a problem that has been driving me batty. I have code that passes coordinates to a query function. The query works fine for latitude see below, but not longitude. I had a complex WHERE clause for both but moved to separate WHERE clauses for the two to troubleshoot. The code below shows the latitude WHERE commented out. If I reverse the commenting out, latitude works as expected. All values in the referenced database are Doubles and negative for longitude versus all positive for latitude. I have hunted for improper syntax and cannot find it. I have even rounded variables to pass, double checked column names, reversed operators, and plenty else. The two WHEREs are identical, respectively; and the longitude variables are passing cleanly based on the feedback of the error given. So, where's Waldo? Thank You!
The ERROR:
Database query failed: 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 'long>=-93.497315 AND long<=-91.365967' at line 1
Calling Function:
$box=$_GET["rect"];
$box=ltrim($box,"((");
$box=rtrim($box,"))");
$boxArray = explode("), (",$box);
$sw = explode(", ",$boxArray[0]);
$ne = explode(", ",$boxArray[1]);
$swLat = round($sw[0], 6);
$swLong = round($sw[1], 6);
$neLat = round($ne[0], 6);
$neLong = round($ne[1], 6);
$job_set = get_job_by_Rectangle($swLat, $swLong, $neLat, $neLong);
while ($job = mysql_fetch_array($job_set)) {
echo $job["projectFK"] . ", ";}
Problem Function:
function get_job_by_Rectangle($swLat, $swLong, $neLat, $neLong) {
global $connection;
$query = "SELECT * ";
$query .= "FROM projcoords ";
//$query .= "WHERE lat>= " . $swLat . " AND lat<= " . $neLat . " " ;
$query .= " WHERE long>=" . $swLong . " AND long<=" . $neLong . " " ;
//$query .= " ORDER BY projectFK";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
return $result_set;
}
LONG is reserved word in MySQL.
So you need to quote the column name with a backtick:
$query .= " WHERE `long`>=" . $swLong . " AND `long`<=" . $neLong . " " ;

PHP - MySQL Transaction execution error

$tran = "START TRANSACTION;";
$tran_res = mysql_query($tran);
$qry_1 = "INSERT INTO docList (doc_ip , doc_country , doc_ref) VALUES ('$ip' , '$country' , '$http_ref');";
$res_1 = mysql_query($qry_1);
if(!$res_1)
die ("qry1 fail " . mysql_error() );
$ins_id = mysql_insert_id();
if(!$ins_id)
die ("ins id fail " . mysql_error() );
echo "<b>$ins_id</b>";
$qry_2 = "INSERT INTO docContent (doc_id , cont_date , cont_title , cont_aim , cont_obj , cont_theory , cont_sw , cont_code) VALUES ('$ins_id' , '$dt' , '$title' , '$aim' , '$obj' , '$th' , '$sw' , '$code');";
$res_2 = mysql_query($qry_2);
if(!$res_2)
die("qry2 fail " . mysql_error() ); `
The execution of above is returning the following error:
2 qry fail 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 'login'); if($query->num_rows()>0) return $query->result_array(); } ' at line 1
In effect the execution of $qry_2 is failing, but I am perplexed by the error it is showing (there is no such code on line 1 as mentioned in the error note). Moreover, the query ($qry_2) executes properly in the MySql console.
Output the contents of $qry_2 to see the actual SQL statement be executed. Most likely you've got SQL injection vulnerabilities, and one of the variables you're inserting contains at least ' somewhere, causing the syntax error.
e.g. if you have
$var = "O'Reilly";
$sql = "INSERT INTO names (name) VALUES ('$var')";
you'll end up with
INSERT INTO names (name) VALUES ('O'Reilly');
which will be interpreted as:
'O' - string containing the letter "O"
Reilly - a field named "Reilly", with no operator between this "field" and the "O" previous
'); - a weird unterminated string, also with no operator between this and the previous field.
To get around this, you MUST pass your variables through mysql_real_escape_string(), which will prevent such errors from occuring. It'll turn O'Reilly into O\'Reilly, which is "safe" to use in your query.
You haven't posted the real query as received by the MySQL server, but I'd dare say you haven't used mysql_real_escape_string() to inject your data into your SQL.
(Are you trying to insert PHP code in the database?)

multiple dynamically generated checkboxes in PHP/MySQL

I have a series of check boxes that are coming out of one MySQL table:
<?php
$result = mysql_query("SELECT * FROM strategies");
if (!$result) {
die("Database query failed: " . mysql_error());
}
while($row = mysql_fetch_array($result)) {
$strategylist = $row['name'];
$strategyname = htmlspecialchars($row['name']);
echo '<input type="checkbox" name="strategy[]" value="' . $strategylist . '" />' . $strategyname;
}
?>
I want to be able to store multiple "strategies" to each row on a "studies" table, so I am employing another table (sslink) to store the id of the study and the name of the strategy. This is partly because there will be an ever growing number of "strategies", so they need to be stored in the database. This is the code I'm currently using:
<?php
if(isset($_POST['update1']))
{
$strategy=serialize($_POST['strategy']); //line 66, where the warning is happening
if(!get_magic_quotes_gpc())
{
$strategy = addslashes($strategy);
}
// update the article in the database
$query ="INSERT INTO sslink('study_id', 'strategyname') VALUES ('".$_GET['id']. "', '" .$strategy. "')";
mysql_query($query) or die('Error : ' . mysql_error());
$cacheDir = dirname(__FILE__) . '/cache/';
$cacheFile = $cacheDir . '_' . $_GET['id'] . '.html';
#unlink($cacheFile);
#unlink($cacheDir . 'index.html');
echo "<b>Article '$title' updated</b>";
$strategy = stripslashes($strategy);
}
?>
And this is the error that gets returned:
Notice: Undefined index: strategy in /casestudyform.php on line 66
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 ''study_id', 'strategyname') VALUES ('1', 'N;')' at line 1
Does anyone know how to fix this? or a better way to do it?
Thanks in advance!
Try this:
$query ="INSERT INTO sslink (study_id, strategyname) VALUES ('".$_GET['id']. "', '" .$strategy. "')";
Undefined index suggests that $_POST['strategy'] wasn't set. Could you do a sanity check that your form has it? Also, an echo of the actual query would be nice.
You have two errors that are unrelated to one another:
Notice: Undefined index: strategy in /casestudyform.php on line 66
As #montooner points out, this notice is from PHP, because the $_POST array contains no value for the 'strategy' key. That is, the form was submitted with no strategy checkbox checked. You should test that the key exists before trying to reference it.
if (array_key_exists('strategy', $_POST)) ...
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 ''study_id', 'strategyname') VALUES ('1', 'N;')' at line 1
This is an SQL parsing error. You have put single-quotes around the columns in your INSERT statement. In SQL, single-quotes delimit string constants, not column names.
If you need to delimit column names (because they contain SQL keywords, whitespace, special characters, etc.), you should use back-quote in MySQL or double-quotes in ANSI SQL.
Also be careful of SQL injection. Don't assume that the HTTP request parameters contain only integers or friendly strings. Filter the values or escape them before you use them in SQL. The addslashes() function is not a good solution to protect against SQL injection.
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$strategy_esc = mysql_real_escape_string($strategy);
$query ="INSERT INTO sslink(`study_id`, `strategyname`)
VALUES ($id, '$strategy_esc')";

Categories