简体   繁体   中英

PHP mysql_query returning TRUE for SELECT

I'm experimenting with stored procedures to return me a recursive parent list. But rather than returning me a result, like in PhpMyAdmin, mysql_query simply returns a boolean true.

mysql_query("DROP FUNCTION IF EXISTS `GetAncestry`") or die(mysql_error());

$sql = "[CREATE SQL FUNCTION THAT LOOPS TO RETURN A STRING CONTAINING A COMMA DELIMITED STRING OF ID's]";

mysql_query($sql) or die(mysql_error());

$sql = "SELECT SubProcessID,GetAncestry(SubProcessID) as parents from prodsubprocess where SubProcessID = {$processID}";

mysql_query($sql) //<--- Returns TRUE, but in PhpMyAdmin returns 7,6,8

From documentation:

For SELECT , SHOW , DESCRIBE , EXPLAIN and other statements returning resultset , mysql_query() returns a resource on success, or FALSE on error.

You need to use mysql_fetch_assoc for the purpose as

$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
   //fetch result
}

Note: mysql_* is depricated ; Please use PDO () prepared statements for the database queries

As you can see int the documentation :

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

You have to cal mysql_fetch_assoc to get the values.

Stop using the deprcated mysql_* API. Use mysqli_ or PDO with prepared statements

First thing I must note is: Do not use mysql_ anymore, go to mysqli_.

You also want to use prepared statements.

On phpmyadmin it simply returns all results automatically as that's the way it's been coded. If you simply execute the query, all it's telling you is whether or not it was executed successfully, which in this case, as it is TRUE, then it is working.

What you want to do in this case is:

$result = mysql_query($sql);

while($row = mysql_fetch_assoc($result)){
    print_r($row);
}

But seriously, check out prepared statements. There is a lot of information on that on php.net, simply look here: http://php.net/manual/en/mysqli.prepare.php

The "Examples" area has plenty of basic info for you.

In Phpmyadmin you will get result automatically for that stored procedure. But at php level, it gives you result status either TRUE or FALSE. If you want to see the results at PHP level then you must use loping construct to loop through returned DB resource to get each value.

Here is code for fetching data through loop.

// Code goes Here.
while($row = mysql_fetch_assoc($sql))
{
    print_r($row);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM