PHP changing number in MySQL query - php

I have this PHP code:
if ($username) {
if ($news == 1)
$int = "9";
if ($news == 0)
$int = "12";
}
else
$int = "9";
$query = mysql_query("SELECT * FROM files WHERE active='1' ORDER BY id DESC LIMIT $int");
require ("scripts/connect.php");
$numrows = mysql_num_rows($query);
But then I get this error (Note the line starting with $numrows is line 69):
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/Site/index.php on line 69
I have tried many ways of changing the number to no avail. Please help! Thanks!

If your scripts/connect.php is responsible for establishing database connection, then I belive mysql_query() should be below it, not above as it is now. I also recommend using mysql_error() and always check return values for errors, as assumptions like "query is always successful" are no-no approach and will hit you badly in less expected moment.
require ("scripts/connect.php");
$query = mysql_query("SELECT * FROM files WHERE active='1' ORDER BY id DESC LIMIT $int");
if( $query ) {
$numrows = mysql_num_rows($query);
...
} else {
die( mysql_error() );
}
Please note mysql extension is deprecated. Switch to mysqli or something more sophisticated like PDO as soon as you can.

Related

Check value in MySQL from PHP

I am fairly new to PHP.
What I want is not much. I just want to place a check on my page which goes to database and check for value 1 or 0. 1 means "enable" so page continues ; and 0 means "disable" and page dies.
someone suggested the following but it didn't work
$sql = mysql_query("SELECT * FROM members WHERE access= '1'");
$user = mysql_query($sql);
echo $user;
if ($user !=="1") {
echo "You are not the proper user type to view this page";
die();
}
Thank you so much for your time.
Firstly, you're using mysql_query() twice and that alone will cause a syntax error.
You're also not looping over results, so use the following to achieve what you want to do.
$sql = "SELECT * FROM members WHERE access= '1'";
$user = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($user)){
if ($row['access'] !=="1") {
echo "You are not the proper user type to view this page";
die();
}
else {
echo "You are the right type.";
}
}
If your query requires a db connection to the query, you will need to do:
$user = mysql_query($sql, $connection);
This assuming a mysql_ successful connection. However, that API is deprecated as of PHP 5.5 and deleted as of PHP 7.0 and note that different MySQL APIs do not intermix.
It's time to step into the 21st century and use either the MySQLi_ or PDO API.
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/book.pdo.php
You may also have to select an actual row (or rows) instead of SELECT * FROM members
I.e.:
SELECT column_1, column_2 FROM members
Consult these following links http://php.net/manual/en/function.mysql-error.php and http://php.net/manual/en/function.error-reporting.php
and apply that to your code.
You can also achieve this with mysql_num_rows():
$result = mysql_query("SELECT * FROM members WHERE access= '1'");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
// do something
}
else {
// do something else
}
You might also want to add to the WHERE clause:
$result = mysql_query("SELECT * FROM members WHERE access= '1' AND column='x' ");

Query would run directly on MySQL but not through PHP

I have a simple MySQL query
select * from tutor where verified = 0 and alert_by < '2015-08-05' LIMIT 0,1
Now, running this directly through phpMyAdmin provides the desired results, however, when this query is being executed through a set of PHP statements, it doesn't return anything. Below is my code in PHP
$this_date = date("Y-m-d");
$query = "select * from tutor where verified = 0 and alert_by < '$this_date' LIMIT 0,1";
$contact = mysqli_query($conn, $query);
$row = $contact->fetch_array(MYSQLI_ASSOC);
However, the $row is empty, I can't seem to figure this out. I know this seems trivial, but its a little annoying.
Note: Removing "and alert_by < '$this_date'" from the query, works fine.
Check
Connection
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Use mysqli_query like this
$contact = mysqli_query($con,"select * from tutor where verified = 0 and alert_by < '$this_date' LIMIT 0,1");
Use fetch array like this (Example #2 Procedural style)
$row = mysqli_fetch_array($contact, MYSQLI_ASSOC)

php functions within functions

ihave created a simple project to help me get to grips with php and mysql, but have run into a minor issue, i have a working solution but would like to understand why i cannot run this code successfully this way, ill explain:
i have a function,
function fetch_all_movies(){
global $connection;
$query = 'select distinct * FROM `'.TABLE_MOVIE.'` ORDER BY movieName ASC';
$stmt = mysqli_prepare($connection,$query);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt,$id,$name,$genre,$date,$year);
while(mysqli_stmt_fetch($stmt)){
$editUrl = "index.php?a=editMovie&movieId=".$id."";
$delUrl = "index.php?a=delMovie&movieId=".$id."";
echo "<tr><td>".$id."</td><td>".$name."</td><td>".$date."</td><td>".get_actors($id)."</td><td>Edit | Delete</td></tr>";
}
}
this fetches all the movies in my db, then i wish to get the count of actors for each film, so i pass in the get_actors($id) function which gets the movie id and then gives me the count of how many actors are realted to a film.
here is the function for that:
function get_actors($movieId){
global $connection;
$query = 'SELECT DISTINCT COUNT(*) FROM `'.TABLE_ACTORS.'` WHERE movieId = "'.$movieId.'"';
$result = mysqli_query($connection,$query);
$row = mysqli_fetch_array($result);
return $row[0];
}
the functions both work perfect when called separately, i just would like to understand when i pass the function inside a function i get this warning:
Warning: mysqli_fetch_array() expects
parameter 1 to be mysqli_result,
boolean given in
/Applications/MAMP/htdocs/movie_db/includes/functions.inc.php
on line 287
could anyone help me understand why?
many thanks.
mysqli_query failed to run your query:
Returns FALSE on failure. For
successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will
return a result object. For other
successful queries mysqli_query() will
return TRUE.
Before running mysqli_fetch_array test $result... Something like:
if ($result !== false)
$row = mysqli_fetch_array($result);
else
return false;
Seems like a variable scope issue within your SQL statement. Outputting the SQL should show you the "true" error.
You may want to try using classes with your functions, for example:
class getInfo {
function fetch_all_movies(){
global $connection;
$query = 'select distinct * FROM `'.TABLE_MOVIE.'` ORDER BY movieName ASC';
$stmt = mysqli_prepare($connection,$query);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt,$id,$name,$genre,$date,$year);
while(mysqli_stmt_fetch($stmt)){
$editUrl = "index.php?a=editMovie&movieId=".$id."";
$delUrl = "index.php?a=delMovie&movieId=".$id."";
echo "<tr><td>".$id."</td><td>".$name."</td><td>".$date."</td><td>".get_actors($id)."</td><td>Edit | Delete</td></tr>";
}
}
function get_actors($movieId){
global $connection;
$query = 'SELECT DISTINCT COUNT(*) FROM `'.TABLE_ACTORS.'` WHERE movieId = "'.$movieId.'"';
$result = mysqli_query($connection,$query);
$row = mysqli_fetch_array($result);
return $row[0];
}
}
$showInfo = new getInfo;
//fetch all movies
$showInfo->fetch_all_movies();
//List actors from movie 1
$showInfo->get_actors("1");
In case of an error mysqli_query will return false. You have to handle the error a simple way to do this might be:
$result = mysqli_query($connection,$query);
if (!$result) {
die(mysqli_error($connection));
}
$row = mysqli_fetch_array($result);
Please note that terminating (by doing die() ) usually is no good way to react on an error, log it, give the user anice error page etc. It's alsonogood practice to give the low level error message toauser, this might motivate users to try to exploit a possile security issue.
Last remark: you were writing
$query = 'SELECT DISTINCT COUNT(*) FROM `'.TABLE_ACTORS.'` WHERE movieId = "'.$movieId.'"';
you should properly escape the movieId there.

num_row manipulation in mysql?

i have this function that brings me back a value by query a table in the database!
the code:
function recycle_check($recycle_id){
$query = "SELECT recycle_id FROM notes WHERE user_id = '".$_SESSION['user_id']."' and recycle_id ='$recycle_id'";
if(mysql_num_rows($query)== 0)
return 0;
else
return 1;
}
but its giving me an error saying:
Warning: mysql_num_rows() expects parameter 1 to be resource
i just want the function to either give me a zero or a number 1!
0 for exists and 1 for deosnt exist!
you need to run mysql_query before calling to mysql_num_rows
like :
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
what you need to pass to the function is:
The result resource that is being
evaluated. This result comes from a
call to mysql_query().

MySQL & PHP Parameter 1 as Resource

Alright, PHP is throwing this error at me (in the log) when I run the code mentioned below:
Error
mysql_num_rows() expects parameter 1 to be resource, string given in (place) on line 10
Line 9-11
$queryFP = ("SELECT * FROM db");
$countFP = mysql_num_rows($queryFP);
$aID = rand(1, $countFP);
I think it has something to do with the $queryFP's syntax, but I'm not completely sure how to fix it since $queryFP's syntax is the simplest query I've ever seen.
You need to query the database first.
$queryFP = ("SELECT * FROM db");
Should be:
$queryFP = mysql_query("SELECT * FROM db");
You are missing the mysql_query function, it should be like this:
$queryFP = "SELECT * FROM table_name_here";
$queryFP = mysql_query($queryFP) or die(mysql_error());
$countFP = mysql_num_rows($queryFP);
$aID = rand(1, $countFP);
As it been said, you're missing mysql_query function.
Though whole approach is wrong. You shouldn't select whole load of ata if you need only number of rows.
So, it must be
$sql = "SELECT count(*) FROM db";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_row($res);
$countFP = $row[0];
$aID = rand(1, $countFP);
And I hope you won't use $aID for any database related action

Categories