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

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.

Related

sqlsrv_fetch_array() expects parameter 1 to be resource, boolean given in

im trying print records from my db (IIS, MSSQL PHP) but i have this error...
Warning: sqlsrv_fetch_array() expects parameter 1 to be resource, boolean given in
<?php
$serverName ="name\SQLEXPRESS";
$usr="sa";
$pwd="pasw";
$db="dbname";
$connectionInfo = array("UID" => $usr, "PWD" => $pwd, "Database" => $db);
$conn = sqlsrv_connect($serverName, $connectionInfo);
$sql = "SELECT first_col, s_col, t_col, FROM names ";
$res = sqlsrv_query($conn,$sql);
while ($row = sqlsrv_fetch_array($res)) {
print(
$row['first_col'].",".$row['s_col'].",".$row['t_col'].");
}
sqlsrv_close( $conn);
?>
Your query failed. This causes sqlsrv_query() to return false.
Your error in your query is an errant comma:
$sql = "SELECT first_col, s_col, t_col, FROM names ";
^^^^
HERE
Remove it and your query should work.
FYI, you don't check for errors in your code. You should always check to see if something failed, and if so, get the error message. You would have caught this quickly if you did.
The accepted answer is too localized and of no help for most users coming from Google, who need rather a generic answer, what to do when one gets such error in general.
This error message doesn't have any particular meaning, it's just a symptom telling us that the query execution failed. While we need to get the actual error message from SQL server. Hence every query should be executed in PHP like this:
$sql = "SELECT first_col, s_col, t_col, FROM names";
$stmt = sqlsrv_query($conn, $sql);
if($stmt === false) {
trigger_error(print_r(sqlsrv_errors(), true), E_USER_ERROR);
}
What is going on here?
first, we are checking the query result, if case it's equal to false, which means the query failed
if so, we are calling sqlsrv_errors() which returns an array with all errors returned by SQL server
then we are converting this array to string using print_r()
and finally, throwing a conventional PHP error that could be handled the same way as any other error
In the end, a failed query will throw a PHP error that explains the reason, so one can read the SQL server error message and then fix it right away or Google this message to get the explanation/practical suggestions for their particular error
If you use Stored Procedure with SQL SERVE, you must use EXEC, in your code you used CALL
$check = sqlsrv_query($conn, "{CALL Mem_Users_Accede (?,?,?,?)}", $data);

Fetch array mysql database php

I am trying to fetch data from database, but something is not working.
This is my code:
<?php
$koppla = mysql_connect("localhost","admin","","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$get = mysql_query($koppla,SELECT * FROM 123);
while ($test = mysql_fetch_array($get))
{
echo $test['tid'];
}
mysql_close($koppla);
?> `<?php
$koppla = mysql_connect("localhost","admin","","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$get = mysql_query($koppla,SELECT * FROM 123);
while ($test = mysql_fetch_array($get))
{
echo $test['tid'];
}
mysql_close($koppla);
?>
I am getting the following error while trying to fetch an array from a MySQL database. What is wrong?
Parse error: syntax error, unexpected '123' (T_LNUMBER) in C:\wamp\www\test.php on line 16
What was wrong
There are at least 3 errors:
Use either mysql_XY or mysqli_XY. NOT both. See MySQL: Choosing an API.TL;DR: Use mysqli_*, because mysql_* is deprecated.
The SELECT statement in line 16 and line 39 has to be in quotes.
The syntax of mysql_query is
mixed mysql_query ( string $query [, resource $link_identifier = NULL ] )
What is correct
So line 16 has to be something like
$get = mysql_query("SELECT * FROM 123", $koppla);
or, when you choose mysqli_query:
$get = mysqli_query($koppla, "SELECT * FROM 123");
Side notes
Table naming: I would not use a table name like 123. I don't know if this is valid SQL, but it feels wrong to not start a table with a character. See SQLite issue with Table Names using numbers? - I know you're using MySQL, but MySQL might have similar problems. And you might want to switch sometimes to another database system.
Optional arguments: You don't need to specify the $link_identifier in mysql_* if you don't have multiple connections.
Style Guide: In PHP, you usually have the curly brace { in the same line as the if. See List of highly-regarded PHP style guides? and especially the Zend and PEAR section. This is also good for SO, because you could avoid a scrollbar in your code which makes reading your question easier.
$get = mysql_query($koppla,SELECT * FROM 123);
should be
$get = mysql_query("SELECT * FROM `123`",$koppla);
You have this in 2 places correct them.
OH well hold on you are using mysql_query()
so it should be
$get = mysql_query("SELECT * FROM `123`",$koppla);
http://in1.php.net/mysql_query
Now going more in the code you are using if (mysqli_connect_errno()) this is for mysqli_connect() you may need to see
http://in1.php.net/manual/en/function.mysql-connect.php as well
$get = mysql_query($koppla,SELECT * FROM 123);
Shell look like this:
$get = mysql_query("SELECT * FROM 123", $koppla);
A query is used to be String; and $koppla shell be the second parameter

PHP errors Unknown column 'Array' in 'field list' and Warning: mysql_query() expects parameter 1 to be string?

I am creating a social network and want users to upload their profile pictures to mysql database, and have been trying for days but I always get these errors:
"Warning: mysql_query() expects parameter 1 to be string, resource given in /home/gowemtoc/public_html/uploadpic.php on line 25" and "Unknown column 'Array' in 'field list'"
please tell me whats wrong I've been trying for days and can't find whats wrong :/
here is my code
<?php
session_start();
if(isset($_SESSION['myusername'])){
$showusername=$_SESSION['myusername'];}
$showcap = strtolower($showusername);
$mysql_host ="localhost";
$mysql_database="database";
$mysql_user="gowemto_me";
$mysql_password="password";
$usercheck=$_GET['user'];
$link=mysql_connect("$mysql_host","$mysql_user","$mysql_password","mysql_database");
mysql_connect("$mysql_host","$mysql_user","$mysql_password")or die("cannot connect");
mysql_select_db("$mysql_database")or die("cannot select DB");
$result = mysql_query("SELECT * FROM Registered WHERE myusername = '$usercheck'");
if($result === FALSE) {
die(mysql_error());
}
$image = $_FILES['myprofilepicture'];
print_r ($image);
$query=mysql_query("UPDATE Registered set myprofilepicture=$image where myusername='$showusername'");
if (!$result = mysql_query($link, $query)){die('Error occured' .mysql_error($link));}
$id = (int) mysqli_insert_id($link);
exit;
?>
Don't you supposed to have this:
mysql_query("SELECT * FROM Registered WHERE myusername = '{$usercheck}'")
// missing curly brackets
instead of
mysql_query("SELECT * FROM Registered WHERE myusername = '$usercheck'") ?
And same goes for other mysql_query() formats.
There's a list of errors here.
$image = $_FILES['myprofilepicture'];
This will just assign an array to your $image variable. It will not give you a filename as expected. You need ['tmp_name'] at least, but ought to move it elsewhere first. See http://www.php.net/manual/en/features.file-upload.post-method.php
Your query also lacks quotes around the interpolated string:
$query=mysql_query("UPDATE Registered set myprofilepicture=$image where myusername='$showusername'");
Such your query will become set myprofilepicture=Array at best. But you need myprofilepicture='/tmp/Whatever'.
And lastly, you are invoking mysql_query() twice. Either you assign the SQL command only to your $query variable:
$query = "UPDATE Registered ...";
Or remove the second mysql_query in the if.
And then you can't mix in mysqli_insert_id, when you used mysql_ functions before.
Don't forget to apply mysql_real_escape_string() on all interpolated strings, if you want to keep using this dated database interface.

PHP mysql_query Syntax Error

<?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";
}

"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.

Categories