mysql_query(select) result improperly empty

lostcommander

Member
Messages
52
Reaction score
0
Points
6
PHP:
// Connect to the database.
$dbconn = mysql_connect('localhost',$user,$password);
if (!$dbconn)
{
    die('DB connection failed: ' . mysql_error());
}
$dbselection = @mysql_select_db($database);
if (!$dbselection)
{
    die('DB selection failed: ' . mysql_error());
}
// Get the list of s from the local MySQL database.
$s_query = "SELECT * FROM the_table";
$s_result = mysql_query($s_query);
if ($s_result === false)
{
    echo("// Query failed!\n");
    die('Query failed: ' . mysql_error());
}
// Parse the returned $s_result resource and save it.
$s_numrows = mysql_numrows($s_result);
$s_array = array();
for ($counter = 0; $counter < $s_numrows; $counter++)
{
    $fetch_s = mysql_fetch_row($s_result);
    $s_array[] = array($fetch_s[0], $fetch_s[1], $fetch_s[2]);
}
// Create the 2D "s_table" JavaScript array: [gid][sname][sid].
if($s_numrows > 0)
{
    echo("var sgids_list = [0");
    for ($counter = 0; $counter < $s_numrows; $counter++)
    {
        echo(", " . $s_array[$counter][0]);
    }
    echo("];\n");
    echo("var snames_list = [\"\"");
    for ($counter = 0; $counter < $s_numrows; $counter++)
    {
        echo(", \"" . $s_array[$counter][1] . "\"");
    }
    echo("];\n");
    echo("var sids_list = [0");
    for ($counter = 0; $counter < $s_numrows; $counter++)
    {
        echo(", " . $s_array[$counter][2]);
    }
    echo("];\n");
    echo("var s_table = [sgids_list, snames_list, sids_list];\n");
} else {
    echo("// Query returned empty!\n");
}

// Disconnect from the database.
mysql_close();

Looking with PHPMyAdmin, I have my 2 test entries in the database table. This code does not fail, but returns the "Query returned empty!" comment. I cannot figure out why it is empty. Help please?

If you need any more information in order to assist, then let me know and I will add it if I can. Thank you very much for your time.
 
Last edited:

xav0989

Community Public Relation
Community Support
Messages
4,467
Reaction score
95
Points
0
It took some time to figure out, since I had to re-indent all your code, but the mysql_numrows() function doesn't exists. The function you are thinking of is mysql_num_rows(). Here is the corrected code.
PHP:
<?php

// Connect to the database.
$dbconn = mysql_connect('localhost',$user,$password);
if (!$dbconn) {
	die('DB connection failed: ' . mysql_error());
}
$dbselection = @mysql_select_db($database);
if (!$dbselection) {
	die('DB selection failed: ' . mysql_error());
}

// Get the list of s from the local MySQL database.
$s_query = "SELECT * FROM the_table";
$s_result = mysql_query($s_query);
if ($s_result === false) {
	echo("// Query failed!\n");
	die('Query failed: ' . mysql_error());
}
// Parse the returned $s_result resource and save it.
$s_numrows = mysql_num_rows($s_result);
$s_array = array();
for ($counter = 0; $counter < $s_numrows; $counter++) {
	$fetch_s = mysql_fetch_row($s_result);
	$array[] = s_array($fetch_s[0], $fetch_s[1], $fetch_s[2]);
}
// Create the 2D "s_table" JavaScript array: [gid][sname][sid].
if($s_numrows > 0) {
	echo("var sgids_list = [0");
	for ($counter = 0; $counter < $s_numrows; $counter++) {
		echo(", " . $s_array[$counter][0]);
	}
	echo("];\n");
	echo("var snames_list = [\"\"");
	for ($counter = 0; $counter < $s_numrows; $counter++) {
		echo(", \"" . $s_array[$counter][1] . "\"");
	}
	echo("];\n");
	echo("var sids_list = [0");
	for ($counter = 0; $counter < $s_numrows; $counter++) {
		echo(", " . $s_array[$counter][2]);
	}
	echo("];\n");
	echo("var s_table = [sgids_list, snames_list, sids_list];\n");
} else {
	echo("// Query returned empty!\n");
}

// Disconnect from the database.
mysql_close(); 
?>
 

lostcommander

Member
Messages
52
Reaction score
0
Points
6
Well, given how much thought I've given it, I figure it will be something "stupid". However, mysql_numrows(), while not in the current manual, does exist and does return an appropriate value. I'd guess it has been deprecated at some point and so have altered my code to mysql_num_rows(). Unfortunately, this also means that the function is still returning 0. :dunno:

Also, I just tried echoing fetch_row and that did not print anything, so there is truely nothing for it to print. Any more ideas?

Also, very sorry I wrapped my post in QUOTE and not PHP... I'll go fix that...
 

xav0989

Community Public Relation
Community Support
Messages
4,467
Reaction score
95
Points
0
Thanks for the fix, my eyes are relieved! ;):biggrin:

So lets go for some basic troubleshooting. First of all, since you've changed mysql_numrows to the other one, it should be good, function-wise.
My first recommended step is to set the query in a variable (if I have multiple queries, I put them in an array and simply var_dump the array) and print the query. Next, take that query and execute it in phpMyAdmin. Tell us the results of it to continue to the next step.
 

lostcommander

Member
Messages
52
Reaction score
0
Points
6
You're not the only one relieved to have indented and colored code to look at, rofl.

Running the query in PHPMyAdmin yielded:
Showing rows 0 - 1 (2 total, Query took 0.0008 sec)
And below were both entries/rows that is should have retrieved, with all the columns it should have, ordered the correct way. My website page/PHP code is still retrieving 0 rows though.
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
One mistake (though probably not the one causing the problem you're seeing) is you've switched names for the $s_array variable and the array constructor when filling $s_array:
PHP:
$s_array = array();
for ($counter = 0; $counter < $s_numrows; $counter++)
{
    $fetch_s = mysql_fetch_row($s_result);
    $array[] = s_array($fetch_s[0], $fetch_s[1], $fetch_s[2]);
}
I believe you meant "$s_array[] = array($fetch_s[0], $fetch_s[1], $fetch_s[2]);", though this seems redundant. Why not just assign the result of mysql_fetch_row($s_result) to $s_array[]? Something like:
PHP:
while ($row = mysql_fetch_row($s_result)) {
  $s_array[] = $row;
}
 

lostcommander

Member
Messages
52
Reaction score
0
Points
6
Yes, mission, you are correct. That is an artifact of my attempt to strip out the variable names I am actually using while leaving them somewhat sensible. I should have copied it all into notepad or something and mass-replaced each one.

I am using a for-loop explicit copying instead of the while-loop direct copying because I was not totally sure what is contained in the mysql_fetch_row() result nor exactly what kind of array the return is composed of.

For kicks I tried the while-loop thing and yeah, it doesn't change anything. I'll keep it around in a comment though as that might be a solution to a bug I'll run into as soon as the database gives me what it is supposed to be giving me to work with.
Edit:
Okay, I thought of another test to try, and man is this odd! So, I created a new table and gave it a couple records, all using PHPMyAdmin, and querying that gave me an error (mysql_query returned false). However, if I simply changed the query string itself from "t_temp" to a table that already existed ("users", generated by the MediaWiki install), I got back everything that I should have.

Is there a problem with creating/poplating tables directly using PHPMyAdmin???
 
Last edited:

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
I am using a for-loop explicit copying instead of the while-loop direct copying because I was not totally sure what is contained in the mysql_fetch_row() result nor exactly what kind of array the return is composed of.

mysql_fetch_row() is equivalent to calling mysql_fetch_array() with a $result_type of MYSQL_NUM, which returns an integer indexed array (rather than associative array) in the order of fields defined by the SELECT statement.

For kicks I tried the while-loop thing and yeah, it doesn't change anything. I'll keep it around in a comment though as that might be a solution to a bug I'll run into as soon as the database gives me what it is supposed to be giving me to work with.
The while loop form isn't any more correct, it's just simpler, hence less prone to typos or logical errors and ever-so-slightly more efficient.

Edit:
Okay, I thought of another test to try, and man is this odd! So, I created a new table and gave it a couple records, all using PHPMyAdmin, and querying that gave me an error (mysql_query returned false). However, if I simply changed the query string itself from "t_temp" to a table that already existed ("users", generated by the MediaWiki install), I got back everything that I should have.

Is there a problem with creating/poplating tables directly using PHPMyAdmin???
Not that I know of. Also, it doesn't matter what you use to insert data as long as it's successful. Once data is in a table, it's in the table. Did you connect to MySQL with a username that had access to the new table?

I tried a cut down version of your code on my own server, and it worked. The problem probably lies in the server configuration or in the database. There could also be a typo somewhere.
 

lostcommander

Member
Messages
52
Reaction score
0
Points
6
Okay, I've played around some more and I agree that the problem has to be, as mission stated:
in the server configuration or in the database
I do not think there is a typo as I've tried some Hello World complexity code and still have the same issues. So... what server configuration options do we have on x10? How fine-grain are permissions for a MySQL database -- table-level or database-level? I only have 1 database and only 1 user at the moment. The user is associated with the database and had/has the "all permissions" checkbox checked. I see nothing about table permissions in PHPMyAdmin.

Oh MY GOODNESS!!??? Now THIS will throw you for a loop... I decided to try and use my PHP code to create a test table, insert records, and select them. This worked. I then removed the creation and insert queries and re-ran it to make sure the changes had stuck (I can't remember if you had to call something special to make such changes stick) and I still got the correct results on my web page. HOWEVER, when I went to PHPMyAdmin, low-and-behold the table did not exist as far as PHPMyAdmin was concerned. I could create it again, drop it, and insert/delete records in PHPMyAdmin and this did NOTHING to my page. ?!?!?

The only thing I can figure is that SOMEHOW the evil gnomeish gremlins of serverland have created an alternate database with the same name, also available from localhost.

If PHP code directs mysql_connect to 'localhost', it should be irrelevant whether or not I have MySQL installed on my local machine, correct? I mean, it has a different DB name, different users, different passwords, and PHP is executed server-side... I am really at a loss though. I'm not sure I've ever been more confused.
 
Last edited:

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
I do not think there is a typo as I've tried some Hello World complexity code and still have the same issues.
There could still be a typo in the name of some MySQL entity, such as the DB name or table name. The PHP code would be valid and the SQL queries could be valid. Not too likely, but possible. One of those things you don't see because you're too close to the code and your brain filters it out. It could even be in the UR

So... what server configuration options do we have on x10? How fine-grain are permissions for a MySQL database -- table-level or database-level? [...] I see nothing about table permissions in PHPMyAdmin.
The permission grain is only what you can access in cPanel's "MySQL Databases" panel, which is database level. The permissions feature has been removed from phpMyAdmin on X10; it wouldn't be useful in any case because our SQL user accounts don't have the GRANT privilege.

Oh MY GOODNESS!!??? Now THIS will throw you for a loop... I decided to try and use my PHP code to create a test table, insert records, and select them. This worked. I then removed the creation and insert queries and re-ran it to make sure the changes had stuck (I can't remember if you had to call something special to make such changes stick)
Only if you're using transactions without autocommit, in which case you need to issue a COMMIT statement when done updating.

and I still got the correct results on my web page. HOWEVER, when I went to PHPMyAdmin, low-and-behold the table did not exist as far as PHPMyAdmin was concerned. I could create it again, drop it, and insert/delete records in PHPMyAdmin and this did NOTHING to my page. ?!?!?
That is very, very odd. Which server are you on? The following script performs the actions you described (creating a table, adding rows, fetching rows):
PHP:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>empty result test</title>
    <style type="text/css">
    </style>
  </head>

  <body>
    <h1>empty result?</h1>
<pre>
    <?php
/* correct the values for the following three variables to get this script to run properly */
$database='_test';
$user= '_';
$password = '';

$table='vars';

$createVars=<<<EOF
CREATE TABLE IF NOT EXISTS $table (
    name VARCHAR(16) PRIMARY KEY,
    value VARCHAR(64),
    type enum('num', 'str', 'list', 'dict') default 'str'
);
EOF;

$dbConn = new mysqli('localhost', $user, $password);
$dbConn->select_db($database);

if ($dbConn->query($createVars)) {
} else {
	echo "Couldn't create table $table: {$dbConn->error}<br/>\n";
}

if (!$dbConn->query("INSERT INTO vars (name, value) VALUES ('foo', 'bar') ON DUPLICATE KEY UPDATE value='bar'")) {
	echo "Couldn't insert table $table: {$dbConn->error}<br/>\n";
}

if (!$dbConn->query("INSERT INTO vars (name, value) VALUES ('bam', 'bug-AWWK!') ON DUPLICATE KEY UPDATE value='bug-AWWK!' ")) {
	echo "Couldn't insert table $table: {$dbConn->error}<br/>\n";
}
$s_result = $dbConn->query("SELECT * FROM $table WHERE name='foo'");
if ($s_result) {
	echo "Result: ", $s_result->num_rows, " rows.\n";
	$s_array = array();
	while ($row = mysqli_fetch_assoc($s_result)) {
		$s_array[] = $row;
	}
    var_dump($s_array);
} else {
	echo "No result for <code>$database.$table</code>.";
}
?>
</pre>
  </body>
</html>
I tested it on Lotus and all changes the script makes are visible in phpMyAdmin. Try it on your host and see if table vars is visible from phpMyAdmin.

Another thing to try is to flush your original table within phpMyAdmin after adding rows (Server->Database->Table, Operations tab). As this shouldn't be necessary, I doubt this will help.

The last thing to try is dropping & recreating the database, tables and user.

Most likely you'll need to open a support ticket on this one.

The only thing I can figure is that SOMEHOW the evil gnomeish gremlins of serverland have created an alternate database with the same name, also available from localhost.
In MySQL, a database is stored as a folder of the same name (except that invalid filename characters are translated to character triples). I suppose if the MySQL name-to-filename translation were sometimes performed improperly, you'd wind up with multiple directories for a given database name, but this would cause all sorts of problems. I really don't see how this could happen without getting all sorts of other errors.

If PHP code directs mysql_connect to 'localhost', it should be irrelevant whether or not I have MySQL installed on my local machine, correct? I mean, it has a different DB name, different users, different passwords, and PHP is executed server-side... I am really at a loss though. I'm not sure I've ever been more confused.
Correct. 'localhost' maps to the IPv6 address ::1 or IPv4 address 127.0.0.1, which is assigned to the loopback interface ("lo0" on Unix systems). The loopback device can't access the network. Furthermore, the MySQL driver will use Unix sockets rather than TCP/IP when it sees a server of "localhost" or "localhost:3306", which also never touches the network. The only way the script will access the MySQL server on your local machine is if the script is also run on your local machine (such as when testing the script on a local development server).
 

lostcommander

Member
Messages
52
Reaction score
0
Points
6
I am on server Starka. I ran that code and I DO NOT see table vars in PHPMyAdmin afterward.

I already tried dropping and recreating the tables and user. Unfortunately, doing the same for the whole database would be too hard as there is other stuff contained in it (PHPBB3, MediaWiki, etc.). One of the boggling parts is that, although this is happening now, the first 3 tables I created by hand work fine.
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
Is the following a fair summary?
  • New tables created using custom PHP scripts are not visible in phpMyAdmin.
  • New tables created using phpMyAdmin are not visible in other PHP scripts.
  • Changes to older tables made from custom PHP scripts are visible in phpMyAdmin.
  • Changes to older tables made from phpMyAdmin are visible in other PHP scripts.
Definitely sounds like something that can only be solved by an admin. One difference between your scripts and phpMyAdmin is they use different usernames to connect to MySQL. I believe phpMyAdmin uses your cPanel username, though it may use a completely different authorization method than the standalone phpMyAdmin. You can try SHOW GRANTS FOR '$user'@localhost queries (testing your cPanel username and the DB username you created) and look for any oddities. You'll have to connect to MySQL using the same account you get the grants for, as non-admin users can't get the grants for another user. Note that SHOW GRANTS will display your hashed password, so be careful with the results. The following should work safely, but I still wouldn't leave it lying around.

PHP:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Show Grants</title>
  </head>

  <body>
    <h1>Show Grants</h1>
	<form method="POST">
	 <label for="user">User</label>
	 <input name="user" size="16" />
	 <label for="pw">Password:</label>
	 <input name="pw" size="16" type="password" />
	 <input type="submit" />
	</form>

<?php
if (isset($_REQUEST['user'])) {
		$dbConn = new mysqli('localhost', $_REQUEST['user'], $_REQUEST['pw']);
		if ($dbConn->connect_errno) {
			echo "Couldn't connect as $_REQUEST[user]:", $dbConn->connect_error;
		} else {
			$user = $dbConn->escape_string($_REQUEST['user']);
			if (! ($grants = $dbConn->query("SHOW GRANTS FOR '$user'@'localhost'"))) {
				echo "Couldn't get grants for $user: ", $dbConn->error;
			} else {
				echo '<pre>';
				while ($grant = $grants->fetch_row()) {
					$grant = preg_replace('/IDENTIFIED BY PASSWORD (?:["\'][^"\"][\'"]|\S+)/i', '', $grant[0]);
					echo $grant, "\n";
				}
				echo '</pre>';
			}
		}
}
?>
  </body>
</html>
 

xav0989

Community Public Relation
Community Support
Messages
4,467
Reaction score
95
Points
0
Is the following a fair summary?
  • New tables created using custom PHP scripts are not visible in phpMyAdmin.
  • New tables created using phpMyAdmin are not visible in other PHP scripts.
  • Changes to older tables made from custom PHP scripts are visible in phpMyAdmin.
  • Changes to older tables made from phpMyAdmin are visible in other PHP scripts.
Somebody used to have a problem like that with the other transfer. It was to X10 v4 I believe... What happened was that their cPanel used a cached copy of the server and the php scripts another cached copy from another time.
 
Top