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);
Related
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.
I'm trying to use PHP/ODBC to connect to an access file. The problem is that I can read from the database but I can't write to it using the below:
$conn = odbc_connect('SKW-DB','','');
if (!$conn)
{
exit ("ODBC Connection Failed ". $conn);
}
$stmt = "INSERT INTO PRODUCT (ProductCode, ProductName) VALUES ('TestCode', 'TestEntry')";
$result = odbc_exec ($conn,$stmt);
echo "Result1: ";
echo $result;
$result returns nothing. Again, I am able to read from the database, connectivity isn't an issue. I just can't write to it.
That's because you're simply ASSUMING the query can never fail. It did fail, and returned a boolean false. echo false literally prints out nothing.
Try this instead:
$result = odbc_exec($conn, $stmt);
if ($result === false ) {
die(odbc_errormsg($conn));
}
And what you get back from odbc_exec() cannot be echoed out anyways. On success, it returns a statement handle, which is NOT something you can simply print out.
Sounds like you need a little more debugging code.
First, try var_dumping the $result instead of echoing it.
var_dump($result);
There's certain PHP variable types that echo can't/won't display.
Next -- chances are your query's causing an error of some sort, so try using the odbc error reporting functions after making your query
$result = odbc_exec ($conn,$stmt);
echo "Result1: ";
var_dump( $result );
if($result)
{
var_dump( odbc_error($conn) );
var_dump( odbc_errormsg($conn) );
}
I am using the mysqli functions (mysqli_connect, mysqli_select_db, mysqli_query) to call 1 select query and 2 stored procedures.
It seems that when I am using the same $connection (returned by mysqli_connect) multiple times, I am getting the following error message: "Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in..."
Below is my code:
<?php
$server="localhost";
$user="user";
$pass="pass";
$db="db";
$connection=mysqli_connect("$server","$user","$pass");
mysqli_select_db($connection, "$db") or die('Unable to select database.');
//First SELECT using $connection
$query=mysqli_query($connection, "SELECT item_name FROM items ORDER BY item_name DESC");
While ($result=mysqli_fetch_array($query,MYSQL_NUM))
{
$complete_result[] = $result[0];
$total_rows = $total_rows + 1;
}
//CALL to first sp using $connection
$query2 = mysqli_query($connection, "CALL sp_check_edits_remaining()");
while ($row2 = mysqli_fetch_array($query2, MYSQL_ASSOC)) {
$edits_remaining = $row2['edits_remaining'];
} // End while
//CALL to second sp using $connection
$query3 = mysqli_query($connection, "CALL sp_edit_data");
while ($row3 = mysqli_fetch_array($query3, MYSQL_ASSOC)) {);
$edits_id = $row3['id'];
} // End while
?>
Like I described, when I call the second sp, the above code gives me the error message mentioned above. (Please note that the connection is never closed.)
However, when I create another connection and provide it to the second sp call, this error disappears. This is shown in the code below
$connection2=mysqli_connect("$server","$user","$pass");
mysqli_select_db($connection2, "$db") or die('Unable to select database.');
//CALL to second sp using $connection
$query3 = mysqli_query($connection2, "CALL sp_edit_data");
while ($row3 = mysqli_fetch_array($query3, MYSQL_ASSOC)) {
$edits_id = $row3['id'];
} // End while
Can anyone please help me why this unexpected behavior?
Thanks and in advance!
It seems I have found a solution, which might be specific to my scenario.
My stored procs return only one row in the resultset.
So, after the CALL to the first sp and the corresponding while loop, I have simply added:
mysqli_next_result($connection);
This has removed the error message/warning I was receiving.
Anyone wants to comment whether this is the 'professional' approach?
You have an error somewhere, causing one of the mysql functions (probably the query call(s)) to return a boolean false, which you then blindly use in a fetch call. You need to add extra error handling, e.g.
$query = mysqli_query($connection, "...") or die(mysqli_error($connection));
never assume a query has succeeded.
enter code hereafter the query is finished, you must close the $connection then for another query, connect and assign the $connection again.
mysqli_close($connection);
$connection=mysqli_connect(bla,bla,bla,bla).
I am currently using mysqli to crate a connection to my database. My host server doesnt support PDO connections so that is why I am using mysqli. When making the connection I am getting this error:
Fatal error: Call to undefined method mysqli_result::fetchAll()
Is fetchAll() not part of mysqli?
PHP Connect to DB
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
else {
echo ('Success... ');
}
$sql = "SELECT *
FROM `categories`
WHERE `master` = 0";
$statement = $mysqli->query($sql);
$list = $statement->fetchAll();
No: it's fetch_all(), not fetchAll().
When you call $mysqli->query($sql), this can return a mysqli_result object, or the value false in case of an error. I think that your query is not successful, and returns the value false, and of course if you ask for false->fetchAll() this will give an error message.
So you have to check first, if the query was successful (use the === operator and check for false), and afterwards you can work with the result of the query.
P.S. That's why i never write functions myself, with mixed typed return values...
According to the documentation it is only available with the mysqlnd However the first comment on the mysql fetch all page describes how you can create a function that does the same thing.
http://php.net/manual/en/mysqli-result.fetch-all.php
Also it's fetch_all not fetchAll
You probably want fetch_all(), instead of fetchAll().
mysqli_result::fetch_all();
PDO::fetchAll();
Manual Entry
I am creating a new login script/members directory.
I am creating it from scratch without any frameworks (advice on this matter would also be appreciated).
The situation:
// Look up the username and password in the database
$query = "SELECT admin_id, username FROM admin WHERE adminname = '$admin_user' AND password = SHA1('$admin_pass')";
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 1) {
This bit of code keeps giving me an error (the last line in particular):
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home8/craighoo/public_html/employees/security/dir_admin.php on line 20
When echoing the query I get:
SELECT admin_id, adminname FROM admin WHERE adminname = 'admin' AND password = SHA1('password')
EDIT:
Thanks to everyone. The problem was in my Database column names and the column names I was referencing.
Your query execution is failing. When that happens mysqli_query returns false (boolean value) and when is passed to mysqli_num_rows, you get this error.
Print the query just before executing and check for correctness.
Considering that mysqli_query returns false on failure, and that $data is a boolean, here, I suppose there is an error occuring during the execution of your SQL query.
You could try using mysqli_error to find out what this error is :
$data = mysqli_query($dbc, $query);
if ($data !== false) {
// Do whatever you want with $data
if (mysqli_num_rows($data) == 1) {
//
}
} else {
echo mysqli_error($dbc);
die;
}
Note : echoing the error message and dying, like I did here, is OK while developping your script ; but you should not do that in production.
Instead, in production, you should :
Log the error to a file
Display a nice message to the user
When you have a critical query, it's best to add a die to it like so:
mysqli_query($dbc, $query) or die('Critical error on line #'. __LINE__ .' when attempting to login ...<br>'. mysql_error());
Have you tried running that same query manually thru phpmyadmin or the console? What result do you get?