I've been all up and down StackExchange, and much of the internet's cornucopia of lesser sites, looking for any good reason my code doesn't work, but this one has me stumped. I'd like to display the total number of rows in a particular MySQL table, and set the count as a variable, to use later in the script. When I run the following, the script dies, and I get a PHP warning, telling me that mysql_result() expects parameter 1 to be resource, string given.
$conn = mysql_connect('mysql_server', 'username', 'password');
if (!$conn) {
die('Connect Error ' . mysql_error());
}
mysql_select_db('my_database', $conn);
if (!mysql_select_db('my_database')) {
die('Could not select database: ' . mysql_error());
}
$max_count_query = ("SELECT COUNT(*) FROM table");
// Perform Query
$max_count_action = mysql_query($max_count_query);
$mcount = mysql_result($max_count_action, 0, 0);
printf("\nNumber of Records to Process: ", $mcount);
What does the collective genius of StackOverflow think?
In response to the comments, I have another mini-slab of code to offer:
$conn = mysql_connect('127.0.0.1', 'username', 'password');
if (!$conn) {
die('Connect Error ' . mysql_error());
}
mysql_select_db('my_database', $conn);
if (!mysql_select_db('my_database')) {
die('Could not select database: ' . mysql_error());
}
$max_count_query = ("SELECT COUNT(*) FROM directory_nap");
// Perform Query
$max_count_action = mysql_query($max_count_query);
if (!$max_count_action){
die('mysql query error: ' . mysql_error());
}
$mcount = mysql_result($max_count_action, 0, 0);
if (!$mcount){
die('mysql result error: ' . mysql_error());
}
printf("\nNumber of Records to Process: ", $mcount);
Provided the table tablename is just a sample (see answer by bitfox), there's nothing wrong with your code. I can use the same code on my test server and get results by changing the table name to one that I know exists in my own db.
What is most troubling, however, is that you indicate the error says mysql_result() expects parameter 1 to be resource, string given -- if your SQL has an error, mysql_query returns boolean (docs), not a string. So, you're either not showing the same test code as you're actually using, or you've given us an inaccurate error message.
At some point, you must be assigning a string into the variable $max_count_action. Here's what I get when I send a query with an intentional problem: Warning: mysql_result() expects parameter 1 to be resource, boolean given -- note "boolean", not string.
So, I think your first step is to choose a different table name. That said, if you're using a reserved word as a table or column name you can still access it by surrounding the string in the backtick (`) character:
SELECT COUNT(*) FROM `table`
Second step is to see what's happening to $max_count_action to turn it into a string. Finally, use mysql_error consistently to debug, I would suggest doing something a little nicer with it than die for production code, however.
// working code on my test server
$max_count_query = ("SELECT COUNT(*) FROM users");
$max_count_action = mysql_query($max_count_query);
$mcount = $max_count_action ? mysql_result($max_count_action, 0) : 'Error: '.mysql_error();
print "\nNumber of Records to Process: ". $mcount;
it's very likely that the error is here:
SELECT COUNT(*) FROM table
"table" is a reserved word of SQL language. You should change it.
The cause of the problem is not clear from the code sample (it could be a wrong table name, the parentheses around the query string, and so on), however there are a number of inaccuracies in it. You can try the following code, it should at least fix a couple side bugs and give you more details on the error:
$conn = mysql_connect('mysql_server', 'username', 'password');
if ($conn === false) {
die('Connect Error ' . mysql_error($conn));
}
if (mysql_select_db('my_database', $conn) === false) {
die('Could not select database: ' . mysql_error($conn));
}
$max_count_query = "SELECT COUNT(*) FROM table";
// Perform Query
$max_count_action = mysql_query($max_count_query, $conn);
if($max_count_action === false) {
die('Query error ' . mysql_error($conn));
}
$mcount = mysql_result($max_count_action, 0, 0);
if($mcount === false) {
die('Result retrieval error ' . mysql_error($conn));
}
printf("\nNumber of Records to Process: %s", $mcount);
mysql_free_result($max_count_action);
Hope this helps, bye!
Is the 'table' in your question a placeholder or a real name in your code? Try to change another name of your 'table' table, otherwise I would like to try mysql_fetch_array instead of mysql_result
$max_count_query = "SELECT COUNT(*) FROM t";
// Perform Query
$max_count_action = mysql_query($max_count_query) or die (mysql_error());
$mcount = mysql_fetch_array($max_count_action);
printf("\nNumber of Records to Process: ", $mcount[0]);
$conn = mysql_connect('mysql_server', 'username', 'password');
if (!$conn) {
die('Connect Error ' . mysql_error());
}
This is OK, but the connect and coditional don't need to be split across 2 lines
mysql_select_db('my_database', $conn);
Again, this is questionable. If you're using multiple databases then referencing databases in your SQL is much simpler and safer than tracking state within your PHP code.
if (!mysql_select_db('my_database')) {
die('Could not select database: ' . mysql_error());
}
Haven't you already done that?
$max_count_query = ("SELECT COUNT(*) FROM table");
Why the brackets?
// Perform Query
Isn't that obvious from the code?
$max_count_action = mysql_query($max_count_query);
$mcount = mysql_result($max_count_action, 0, 0);
It would be neater to pass the db handle to the mysql_query call.
You checked for an error after connecting, you checked for an error after switching database, but you don't check for an error after mysql_query() ?
printf("\nNumber of Records to Process: ", $mcount);
There is no placeholder in the format string for the mcount argument.Try:
printf("\nNumber of Records to Process: %d", $mcount);
I get a PHP warning, telling me that mysql_result() expects parameter 1 to be resource, string given.
Then the code you are running is not the code you've shown us; mysql_query() will not return a string.
Related
I'm still getting mysql error in my PHP script.
Problematic code:
$mquery = mysql_query("SELECT m.`id`, m.`name`, NULL AS `type`, NULL AS `code`, 0 AS `cat` FROM `menu` m UNION ALL SELECT l.`id`, l.`name`, l.`type`, l.`code`, l.`cat` FROM `lines` l UNION ALL SELECT s.`id`, s.`name`, s.`site`, s.`site`, s.`cat` FROM `sites` s ORDER BY `name` ASC");
if(!$mquery) { echo mysql_error(); die(); }
while($mdata = mysql_fetch_assoc($mquery)) { ... }
When i put this query into PhpMyAdmin - all is OK, i will get result. When I put this query into MySQL Workbench - all is OK, i will get result.
AND NOW: When I run script with parameter (http://domain/index.php?site=ABC) - ALL IS OK. When I run script without parameter (http://domain/index.php) - I get mysql error on this query: "Table 'test.menu' doesn't exist".
What "test.menu"?! Where is "test"? I don't want any "test", I have no "test" in my query. And why is it related on parameter in url? It's not dynamically generated query. Where is problem?
Sorry for my english
Solved, script structure:
$mydb = mysql_connect(...);
mysql_select_db(..., $mydb);
mysql_set_charset('utf8', $mydb);
function newMenu($db)
{
$mquery = mysql_query("...", $db);
if(!$mquery) { echo mysql_error(); die(); }
while($mdata = mysql_fetch_assoc($mquery) { ... }
}
myMenu($mydb);
But what i don't understand is: Why is it working without "$db" when parameter 'site' is in url?
Please check your mysql configuration in PHP. I am pretty sure you are using database name as 'test' because you've copied the code from somewhere. Change it to the actual name of your database and it will work.
The second parameter of mysql_query must be a connection variable.
<?php
$con = mysql_connect("localhost", "root", "mypass") or
die("Could not connect: " . mysql_error());
mysql_select_db("tutorials");
$result = mysql_query("select * from tutorials");
echo "<h2>Here is a list of the topics:</h2>";
while ($row = mysql_fetch_array($result)) {
echo $row['name']."<br />";
}
mysql_close($con);
?>
Could you give full php script? is the database config related to 'site' parameter ?
I am new to this but managed to track my issue down to this error:
Error description: Unknown column 'huhuhu' in 'where clause'0
Query:
$sql = mysqli_query($mysqli, "SELECT description FROM cscart_postcode_location_descriptions WHERE description = ".$postcode_q." LIMIT 1");
It seems it's looking for a column from the $postcode_q but that is what I'm trying to search for. It's a table called "cscart_postcode_location_descriptions" and wanting to search the column "description" within that table with the value that's passed to $postcode_q.
Any ideas what's wrong there?
Update
<?php
//if we got something through $_POST
if (isset($_POST['postcode_locator_search'])) {
// here you would normally include some database connection
//include('config.local.php');
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','test','c#W)ukmd[0bm','test');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
// never trust what user wrote! We must ALWAYS sanitize user input
$postcode_q = mysqli_real_escape_string($mysqli, $_POST['postcode_locator_search']);
//$postcode_q = htmlentities($postcode_q);
// A select query. $result will be a `mysqli_result` object if successful
$sql = mysqli_query($mysqli, "SELECT description FROM cscart_postcode_location_descriptions WHERE description = '".$postcode_q."' LIMIT 1");
echo("Error description: " . $postcode_q);
if($result === false or mysqli_error($mysqli) === 0) {
// Handle failure - log the error, notify administrator, etc.
echo '1';
} else {
echo "0";
}
$mysqli->close();
}
?>
I have a PHP statment that $_GET's input from a html page and uses that input(customerID) to search through the database for appropriate results. I have that working fine. What i want to do is, if the user enters an invalid customerID, i want the system to give a message and terminate, else if the user input is correct, i want it to be business as usual.
$id = $_GET['customerID'];
$conn = mysql_connect("localhost", "user", "password");
mysql_select_db("databse", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "SELECT .......
WHERE order.customerID = $id
ORDER BY order.orderDate ASC";
if($id != 'order.customerID'){
die('Invalid Customer ID entered');}
else
{
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
}
Thats my php code. When i run that, if i enter a invalid ID, it will show me 'Invalid Customer ID entered' but when i enter a vaild customerID, it still shows me that error message. Obviously im making a mistake which im not seeing, any help would be appreciated.
First, never trust data from the user, so patch this:
$id = $_GET['customerID'];
With
$id = mysql_real_escape_string($_GET['customerID']);
It sanitizes your value (although it's not completely safe).
For your main problem,
if($id != 'order.customerID'){
order.customerID is just a string. The correct way to check would be to execute the query first, then check if any rows have returned using mysql_num_rows(), if not display an error message else carry on.
$rs = mysql_query($sql, $conn) or die ('Problem with query' . mysql_error());
if($rs && mysql_num_rows($rs)>0){
//query success and rows returned
}
else
{
die('Invalid Customer ID entered');
}
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You need to change your logic a bit. First, you need to check if the customerID exists (probably in a "customers" table?) and then proceed with your query.
For example:
$customerID = mysql_real_escape_string( $_GET['customerID'] ); //fixes sql injection
$queryString = "SELECT * FROM customers WHERE customerID = {$customerID} LIMIT 1";
$query = mysql_query( $queryString ) or die( mysql_error() );
if (mysql_num_rows( $query ) == 0) {
die( 'Invalid Customer ID entered' );
}
// from here onward you may proceed with your previous statement.
I am getting the error:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home/mjcrawle/public_html/home/index.php on line 23
Line 23 turns out to be $num_results = mysqli_num_rows($result); but I am thinking the error is further up but I am having trouble finding it.
The actual code that I am using to connect to the DB is (I do understand there is a redundancy if the database cannot connect):
Any help would be wonderful and a reason for the error would be awesome!
/*Connect To DB*/
$conn = mysqli_connect($host, $user, $pwd)
or die("Could not connect: " . mysql_error()); //connect to server
mysqli_select_db($conn, $database)
or die("Error: Could not connect to the database: " . mysql_error());
/*Check for Connection*/
if(mysqli_connect_errno()){
/*Display Error message if fails*/
echo 'Error, could not connect to the database please try again later.';
exit();
}
/* Query for states */
$query = "SELECT StateAbbreviation, StateName, FROM USState ORDER BY StateName";
$result = mysqli_query($conn, $query);
$num_results = mysqli_num_rows($result);
?>
You have an extra comma before the FROM in query = "SELECT StateAbbreviation, StateName, FROM USState ORDER BY StateName";, you may be getting an error and not having a result when you execute the query.
If the query fails, mysqli_query returns boolean false
After $result = mysqli_query($conn, $query);, you should test the return value before continuing:
if ( ! $result){
$error = mysqli_error($conn);
//do something with the error message
}
See EmCo's answer for why your query is failing.
<?php
$con=mysqli_connect('localhost','root','','dbname') or die ("Connection Failed");
?>
This is the simple method of DB Connection
Encountered with the following warning when trying to access the page:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/designand/www/www/random.php on line 13
Everything was working fine when I was testing it on XAMPP.
<?php
$db_hostname = "localhost";
$db_username = "root";
$db_name = "links";
$db_pass = "xxx";
$dbh = mysql_connect ($db_hostname, $db_username, $db_pass) or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db($db_name) or die(mysql_error());
$num_displayed = 1 ;
$result = mysql_query ("SELECT * FROM 'links' ORDER BY RAND() LIMIT $num_displayed");
while($row = mysql_fetch_array( $result ))
{
echo "<img src=\"" . $row["image"] . "\" border=0 alt=\"\">" ;
}
mysql_close($dbh);
?>
An error like that almost always means there's a problem with your query.
To find out what error message MySQL returns, you can put or die(mysql_error()) just before the semicolon after your mysql_query call. You may also want to print the exact query text you send to MySQL, as this may help you to see the actual problem.
Given that I don't know how much you may have anonymized this example, I can't be sure if this is the actual error, but it looks like you've surrounded your table name with apostrophes ('). This is incorrect; the correct character for escaping table and column names is `.
"supplied argument is not a valid MySQL result resource" means that the query didn't return a valid resource. It failed. To view the error just print out mysql_error() after mysql_query().
Could be that the table doesn't exist. Did you check it?
The second thinkg - ORDER BY RAND() is bad! You should think of different ways on how to shuffle the result. Just google it, there are a lot of other ways to do it - ORDER BY RAND() # Google
Try changing this line:
$result = mysql_query ("SELECT * FROM 'links' ORDER BY RAND() LIMIT $num_displayed");
To:
$result = mysql_query ("SELECT * FROM 'links' ORDER BY RAND() LIMIT $num_displayed") or die (echo mysql_error());
It seems like the SQL is failing to return a valid response. Adding the above should show you the last MySQL error and help point you in the correct direction.
Please add this code to get if the mysql is throwing any errors:
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while(....