PHP mysql_query Syntax Error - php

<?php
mysql_connect("localhost","root","");
mysql_select_db("hftwmvirtualdb");
$Booknum = mysql_real_escape_string($_POST['Booknum']);
$Chapternum = mysql_real_escape_string($_POST['Chapternum']);
$Versenum = mysql_real_escape_string($_POST['Versenum']);
$sql = mysql_query("SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = $Booknum AND `CHAPTERID` = $Chapternum AND `VERSENO` = $Versenum");
echo mysql_error();
while($row=mysql_fetch_assoc($sql));
print(json_encode($row));
mysql_close();
?>
I am trying to use posted data from an android application to trigger a query and retrieve the results from the mysql database. The Table has 4 columns, and I'm trying to retrieve the value in the third column by defining the values in the first 3 columns. Each time i clicked the button, I get the parsing error to find out my PHP script was not processing the SQL query. When running the scriptthrough the browser I get the messages:
Undefined index: Booknum in C:\wamp\www\GetVerse.php on line 4
Undefined index: Chapternum in C:\wamp\www\GetVerse.php on line 5
Notice: Undefined index: Versenum in C:\wamp\www\GetVerse.php on line 6
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 'AND CHAPTERID = AND VERSENO =' at line 1
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\wamp\www\GetVerse.php on line 9.
I understand i get the warning messages 1-3 is because I did not submit the post data but the latter I don't know how to fix as I have tried using the correct syntax, I tried removing "=" for "like" and that failed also. What is the problem?.

The undefined index errors are, as you specified, occurring because you did not submit the post data. This, in turn, is causing the variables $Booknum, $Chapternum, and $Versenum to be empty.
With the empty variables, the MySQL query is being generated with a WHERE clause like:
WHERE `BOOKID` = AND `CHAPTERID` = AND ...
The missing values are causing invalid MySQL, hence your error. Additionally, as you've specified (in a comment) that the POST-values are strings (and not integers which is what I would have assumed based on their usage and names), you have to wrap the values in quotes in your MySQL query too. If you do not wrap the values in quotes, even valid strings may cause the query to fail.
To fix this, try something like:
$Booknum = isset($_POST['Booknum']) ? mysql_real_escape_string(trim($_POST['Booknum'])) : null;
$Chapternum = isset($_POST['Chapternum']) ? mysql_real_escape_string(trim($_POST['Chapternum'])) : null;
$Versenum = isset($_POST['Versenum']) ? mysql_real_escape_string(trim($_POST['Versenum'])) : null;
if (!empty($Booknum) && !empty($Chapternum) && !empty($Versenum)) {
$sql = mysql_query("SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = '" . $Booknum . "' AND `CHAPTERID` = '" . $Chapternum . "' AND `VERSENO` = '" . $Versenum . "'");
echo mysql_error();
while($row=mysql_fetch_assoc($sql));
print(json_encode($row));
mysql_close();
}
This will verify that the values are properly set - if not, they will be set to null. If all three values are not empty, via PHP's empty(), your query will be executed.

This is what your SQL query will look like when the variables are substituted in:
SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = AND `CHAPTERID` = AND `VERSENO` =
When the variables contain no content (as they won't if you submit no data), the query is meaningless: the syntax is malformed.
Check whether the data is posted before doing the query. Moreover, it will also profit you to start using parameterised queries (using MySQLi or PDO) for security and convenience.

The "undefined index" messages you're getting are because those variables are not set. Check that you're actually posting those to the script.
The empty variables are why your query is wrong and you get an error.
Consider using PDO as the "mysql_" commands are deprecated. You should check your inputs before passing them to the query. isset() will work for that.

CHeck whether the Post data is coming or not, undefined index it is because, there is no data for the variables you have used. SO first verify it and then execte the SQL query.
if(isset($_POST['Booknum']) && isset($_POST['Chapternum']) && isset($_POST['Versenum']))
{
$Booknum = mysql_real_escape_string($_POST['Booknum']);
$Chapternum = mysql_real_escape_string($_POST['Chapternum']);
$Versenum = mysql_real_escape_string($_POST['Versenum']);
$sql = mysql_query("SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = $Booknum AND `CHAPTERID` = $Chapternum AND `VERSENO` = $Versenum");
echo mysql_error();
while($row=mysql_fetch_assoc($sql));
print(json_encode($row));
}
else
{
echo "No post data";
}

Related

pg_query(): Query failed: ERROR: column doesnot exist

i did follow the solution here : Warning: pg_query(): Query failed: ERROR: syntax error at or near but i still got the following error :
Warning: pg_query(): Query failed: ERROR: column "rosmoffi" does not exist LINE 1: ... FROM public."espece" where "espece"."Code_Espece" =Rosmoffi ^
this is my code :
$conn = pg_connect($conn_string);
$query = 'SELECT * FROM public."espece" where "espece"."Code_Espece" ='.$idd ;
if (!$result = pg_query($conn, $query)){
echo pg_result_error ($conn);
return false;
}
$result = db($result);
return $result;
$query = 'SELECT * FROM public."espece" where "espece"."Code_Espece" ='.$idd ;
Do not do this. If you were to output what you get here you'd see the error, as you should from the error message. Whatever is in the variable $idd will be put into the query as is and it will not be considered a string. It's just a part of the query. So since there are no quotes it will in this case be understood as a column name.
The worst part of this is that if $idd is coming from the user think what will happen when someone sets it to 1; truncate table espece. Or something worse. Learn how to use parameters immediately.
Using parameters your code would be:
$query = 'SELECT * FROM public."espece" where "espece"."Code_Espece" =$1';
if (!$result = pg_query_params($conn, $query, array($idd))){
This way the variable is given properly to the database and there is no injection vulnerability.
NB! For those who keep saying the double quotes should be removed, no. They should not. If the column name is capitalized as Code_Espece then PostgreSQL will not recognize it without the quotes. Capitalization is usually not recommended.

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.

Post data to mysql DB

I'am trying to send data from android as JSON to PHP in order to parse it and save in MySQL DB
this is the part of the PHP CODE
$JsonString = $_POST["DATA"];
$JsonData = json_decode($JsonString, TRUE);
$Add_First_Only = 0;
foreach ($JsonData['items'] as $item)
{
$Order_ID = $item['Order_ID'];
$Order_Row_Number = $item['Order_Row_Number'];
$Order_Item_ID = $item['Order_Item_ID'];
$Order_Course_ID = $item['Order_Course_ID'];
$Order_Seat_No = $item['Order_Seat_No'];
$Order_Row_Value_wo_Options = $item['Order_Row_Value_wo_Options'];
$Order_Row_Value_with_options = $item['Order_Row_Value_with_options'];
if ($Add_First_Only == 0)
{
$result = mysqli_query($con,
"INSERT INTO order_items (Order_ID,Order_Row_Number,Order_Item_ID,Order_Course_ID,Order_Seat_No,Order_Row_Value_wo_Options, Order_Row_Value_with_options)
VALUES
(['$Order_ID'],['$Order_Row_Number'],['$Order_Item_ID'],['$Order_Course_ID'],
['$Order_Seat_No'],['$Order_Row_Value_wo_Options'],['$Order_Row_Value_with_options'])"
);
$Add_First_Only = 1;
}
}
and this is the error I get on the Eclipse LogCAT
12-16 02:00:01.800: V/TAG(1841): 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 '['26'],['1'],['1'],['1'],['1'],['0'],['1'])' at line 4
As you can see from the error it self that I have values for the variables so non of them is a null value
The Question is what should I change or add to my sql syntax to fix this error ?
Remove the brackets around ['$Order_ID'] and the others
Use '$Order_ID' instead of ['$Order_ID'] etc. for your VALUES
if ($Add_First_Only == 0)
{
$result = mysqli_query($con,
"INSERT INTO order_items (Order_ID,Order_Row_Number,Order_Item_ID,Order_Course_ID,Order_Seat_No,Order_Row_Value_wo_Options, Order_Row_Value_with_options)
VALUES
('$Order_ID','$Order_Row_Number','$Order_Item_ID','$Order_Course_ID',
'$Order_Seat_No','$Order_Row_Value_wo_Options','$Order_Row_Value_with_options')"
);
$Add_First_Only = 1;
}
Don't wrap the parameters in the SQL statemenst with square brackets (example: ['$Order_ID']).
I often find it helpful to echo or error_log the SQL statement that is created and try running it in a SQL tool. This should give you better error messages, and reveal syntax errors (if the tool has syntax highlighting).
Also, look at what php.net has to say about prepared statements. SQL-statements of this type are vulnerable to SQL-injection attacks which are one of the most common ways to attack systems.
When you use Single quotes '' around the data you want to INSERT into DB you tell PHP that this data is string type and your database probably expects INTEGER data.

"mysql_fetch_assoc()" error when data in mysql field is changed

I have a mySQL database from where I fetch some data via PHP.
This is what I've got:
if ($db_found) {
$URL_ID = $_GET["a"];
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = $URL_ID";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
$firstname = $db_field['firstname'];
$surname = $db_field['surname'];
$function = $db_field['function'];
$email = $db_field['email'];
$telnr = $db_field['telnr'];
}
mysql_close($db_handle);
}
else {
print "Database not found... please try again later.";
mysql_close($db_handle);
}
The URL_ID field in my mySQL database is, for this example, 001. When I go to www.mydomain.com/index.php?a=001 it fetches all the data, puts it into a variable, and I can echo the variables without any problem.
Now, I want to change the URL_ID, and I've changed it to "62ac1175" in the mySQL database. However, when I proceed to www.mydomain.com/index.php?a=62ac1175, I get this error message:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
boolean given in
mydomain.com\db_connect.php on line 17
The field in mySQL has varchar(8) as type and utf8_general_ci as collation.
If I change the entry back to 001 and change my URL to ?a=001, it works fine again.
What's going wrong?
You are not doing any error checking in your query, so it's no wonder it breaks if the query fails. How to add proper error checking is outlined in the manual on mysql_query() or in this reference question.
Example:
$result = mysql_query($SQL);
if (!$result)
{ trigger_error("mySQL error: ".mysql_error());
die(); }
your query is breaking because you aren't wrapping the input in quotes. You can avoid* quotes only for integers (which 62ac1175 is not). Try
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = '$URL_ID'";
Also, the code you show is vulnerable to SQL injection. Use the proper sanitation method of your library (like mysql_real_escape_string() for the classic mysql library that you are using), or switch to PDO and prepared statements.
In your code, this would look like so: Instead of
$URL_ID = $_GET["a"];
do
$URL_ID = mysql_real_escape_string($_GET["a"]);
* however, if you avoid quotes, mysql_real_escape_string() won't work and you need to check manually whether the parameter actually is an integer.

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