PHP SQL Statement not accepting Variable - php

I'm trying to use the following code however it is giving me errors.
Code:
$id = $_GET['id'];
$action = '['command'=>'get','target'=>'location']';
$query = "UPDATE ZeusUsers SET action = '$action' WHERE notification_id = '$id'";
$result = mysqli_query($link,$query) or exit("Error in query: $query. " . mysqli_error());
Error:
Parse error: syntax error, unexpected 'command'
If I change the $action to a standard word the statement works fine, it just seems to have issues with the single quotes and square brackets.
I've also tried using \ in front of the single quotes and it still fails.
Any ideas?

let php build the json string for you
$action = json_encode(array('command'=>'get','target'=>'location'));
You are starting and stoping a string literal with the single quotes so php is interpreting command as php code but it doesn't know what that keyword is.

Related

PHP / SQL error, unexpected variable name

I get the following error:
Parse error: syntax error, unexpected '$studentNo' (T_VARIABLE)
Can somebody tell me what's wrong here? I've read about this kind of error and base on it, it usually happens when there's a missing bracket, parenthesis or semi-colon but in my case I don't think I missed any..Does it have something to do with the variable itself, perhaps?
if(isset($_POST['next'])){
$studentNo = $_POST['sn'];
if(!empty($_POST['sn'])){
$check = ("SELECT * FROM student_info WHERE SN="$studentNo"");
$check1 = mysqli_query($con, $check);
if(mysql_num_rows($check1) > 0){
$errors['sn'] = "Student number already exists";
}
}
}
Your problem is that you have to concatenate the string.
But, before doing this, make sure that your SQL library protects against SQL injections.
To do this, just do:
$check = "SELECT * FROM student_info WHERE SN=" . $studentNo . ";";
// Also, remember to add a semicolon at the end of your SQL query :)
The best way to do this is to use a prepared statement. This site explains it very well.

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.

What defines the PHP error: Call to a member function fetch_object() on a non-object

I have been wondering on this question for a while. I have two PHP programs that are almost exactly identical except for the fact that on of them is a function and the other isn't. Furthermore one works and the other send back the error:
Call to a member function fetch_object() on a non-object
I fixed the one that wasn't working by omitting the variables and inserting definitive strings and adding $con->errno instead of mysqli_errno. However, when I replaced the strings with the variables again the problem returned.
So, my question is: what causes this error and how would I fix it. Also, why is the error coming up in the second code and not the first?
The First Code (works)
<?php
$con = new mysqli("database info");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = $con->query("SELECT coordinator, announcements, description, comments, picture FROM Class_data WHERE class_year = '" .$class. "';");
$result_row = $stmt->fetch_object();
$coordinator = $result_row->coordinator;
$announcement = $result_row->announcements;
$description = $result_row->description;
$comments = $result_row->comments;
$picturepath = $result_row->picture;
mysqli_error($con);
mysqli_close($con);
if ($picturepath == "")
{
$picturepath = "../images/AlumnLogo.png";
}
?>
Second Code (doesn't work)
<?php
function fetch($page, $content1, $content2, $content3)
{
$con = new mysqli("database info");
if ($con->errno)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = $con->query("SELECT '" .$content1. "' , '" .$content2. "' , '" .$content3. "' FROM '" .$page. "';");
$result_row = $stmt->fetch_object();
$content = array();
$content[0] = $result_row->body;
$content[1] = $result_row->calendar;
$content[2] = $result_row->announcements;
$output = implode("--",$content);
mysqli_error($con);
mysqli_close($con);
return $output;
}
?>
Thanks alot!
You are quoting your column names using single quotes. You cannot do that, you need to quote table- and column names using backticks (in case of reserved words, spaces, etc.) and only (non-integer...) values need to be quoted using single or double quotes.
Change your code to:
$stmt = $con->query("SELECT `" .$content1. "` , `" .$content2. "` , `" .$content3. "` FROM `" .$page. "`;");
^ All these
By the way, I assume you are using a white-list for your table- and column names. If not, you should to avoid sql injection.
It is also a good idea to add error handling to your database calls. An easy way using mysqli, is to put mysqli_report(MYSQLI_REPORT_STRICT); at the start of your script. This will cause mysqli to throw exceptions so that you do not have to check for individual errors on each database call.
The error message simply means that you try to call a method on something that is not an object. The problem is that $stmt is not an object!
This happens because there is an error in your SQL Statemetn. $con->query() retuns false in such a case. Therefore, what you try to execute is something like false->fetch_object();. And false isn't an object...
Try to print your generated SQL Statement. It will probabely contain some syntax errors. Fix those, and it will work

inseting xml data to mysql database via php

I want to read an xml file using file_get_contents() and then insert this file to my mysql database but i have an error on my code, please see my code below:
//details ommited
$address= $_GET['address'];
$xml = file_get_contents($address);
db_connect(); // my db connection function
$query = "INSERT INTO feeds SET name = '$name' , xml_data = '$xml' ";
$result = mysql_query($query);
if(!$result)
{
echo mysql_error();
}
// end of my code
So , when i add , xml = '$xml' to my sql $query, php show this error to me:
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 OFF-state current.]]></description>\n\t\t\t</' at line 1
A few suggestions
use PDO parameter binding
escape your xml input
With how you're currently doing it, $xml may have a character that is ending your sql statement prematurly. I have no idea what character could cause this, but my suggestions should fix that.

Preparing SQLite SQL statements in PHP

I'm trying how best to prepare my SQLite SQL strings in PHP. The SQLite3 class comes with an escapeString() function, but here are my issues:
Try 1)
$sql = "INSERT INTO items ('id','content','title','created') VALUES ('4e7ce7c18aac8', 'Does this work', NULL, '2011-09-23T16:10:41-04:00');";
$sql = SQLite3::escapeString( $sql );
echo ($sql);
This results in a string that's all jacked up:
INSERT INTO items (''id'',''content'',''title'',''created'') VALUES
(''4e7ce7c18aac8'', ''Does this work'', NULL,
''2011-09-23T16:10:41-04:00'');
Those aren't double quotes, rather doubled-up single quotes. Obviously won't work.
Try 2)
$sql = 'INSERT INTO items ("id","content","title","created") VALUES ("4e7ce7c18aac8", "Does this work", NULL, "2011-09-23T16:10:41-04:00");';
$sql = SQLite3::escapeString( $sql );
echo ($sql);
This results in:
INSERT INTO items ("id","content","title","created") VALUES
("4e7ce7c18aac8", "Does this work", NULL,
"2011-09-23T16:10:41-04:00");
This query works fine, but the escapeString function hasn't modified anything as there's nothing to escape...
Try 3)
$sql = 'INSERT INTO items ("id","content","title","created") VALUES ("4e7ce7c18aac8", "Doesn't this work", NULL, "2011-09-23T16:10:41-04:00");'; $sql = SQLite3::escapeString( $sql ); echo ($sql);
Here's the big problem- Now I have an apostrophe in one of my values. It won't even make it to escapeString() because PHP will throw an error on the invalid string:
PHP Parse error: syntax error, unexpected T_VARIABLE, expecting ','
or ';'
How am I supposed to be approaching this? Keep in mind that in the actual code my parameter values will be variables, so am I supposed to escape each variable before I pass it into the string? If so, what function do I use?
Finally, what's the point of escapeString()?? I can't figure out how it's supposed to be used correctly.
You don't escape the entire query. You escape unsafe data you're inserting into the query, e.g.
$unsafe = $_GET['nastyvar'];
$safe = SQLite3::escapeString($unsafe);
$sql = "INSERT INTO table (field) VALUES ($safe);";
echo ($sql);

Categories