Hi i am too new too php and mysql and i want to count the member number due to the search made by user. However, mysql_num_rows doesnt work.
mysql_num_rows(mysql_query("SELECT * FROM members WHERE $title LIKE '%$_POST[search]%' LIMIT $start,$member_number"));
It says "mysql_num_rows(): supplied argument is not a valid MySQL result resource in ..."
NOTE: $title is a select menu which user choose where to search. LIMIT is, as you know :), number of member which is shown in a page.
And also $start= ($page-1)*$member_number; in order to set the first entry in that page. I think the problem is here but i cant solve it. :(
Your query probably has an error, in which case mysql_query will return false.
For this reason, you should not group commands like this. Do it like this:
$result = mysql_query("...");
if (!$result)
{ echo mysql_error(); die(); } // or some other error handling method
// like, a generic error message on a public site
$count = mysql_num_rows($result);
Also, you have a number of SQL injection vulnerabilities in your code. You need to sanitize the incoming $search variable:
$search = mysql_real_escape_string($_POST["search"]);
... mysql_query(".... WHERE $title LIKE '%$search%'");
if $start and $end come from outside, you also need to sanitize those before using them in your LIMIT clause. You can't use mysql_real_escape_string() here, because they are numeric values. Use intval() to make sure they contain only numbers.
Using a dynamic column name is also difficult from a sanitation point of view: You won't be able to apply mysql_real_escape_string() here, either. You should ideally compare against a list of allowed column names to prevent injection.
you have to use GET method in your form, not POST.
mysql_num_rows doesn't make sense here.
If you're using limit, you already know the number*.
If you want to know number, you shouldn't use limit nor request rows but select number itself.
// get your $title safe
$fields = array("name","lastname");
$key = array_search($_GET['title'],$fields));
$title = $fields[$key];
//escape your $search
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT count(*) FROM members WHERE $title LIKE '%$search%'";
$res = mysql_query($query) or trigger_error(mysql_error()." in ".$sql);
$row = mysql_fetch_row($res);
$members_found = $row[0]
in case you need just 5 records to show on the page, no need for mysql_num_rows() again:
// Get LIMIT params
$member_number = 5;
$start = 0;
if (isset($_GET['page'])){
$start = abs($_GET['page']-1)*$member_number;
}
// get your $title safe
$fields = array("name","lastname");
$key = array_search($_GET['title'],$fields));
$title = $fields[$key];
//escape your $search
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT count(*) FROM members
WHERE `$title` LIKE '%$search%'
LIMIT $start, $member_number";
$res = mysql_query($query) or trigger_error(mysql_error()." in ".$sql);
while($row = mysql_fetch_assoc($res){
$data[] = $row;
}
Now you have selected rows in $data for the further use.
This kind of error generally indicates there is an error in your SQL query -- so it has not been successful, and mysql_query() doesn't return a valid resource ; which, so, cannot be used as a parameter to mysql_num_rows().
You should echo your SQL query, in order to check if it's build OK.
And/or, if mysql_query() returns false, you could use mysql_error() to get the error message : it'll help you debug your query ;-)
Typically, your code would look a bit like this :
$query = "select ..."; // note : don't forget about escaping your data
$result = mysql_query($query);
if (!$result) {
trigger_error(mysql_error()." in ".$query);
} else {
// use the resultset
}
Related
I have a successful connection made in PDO to my MySQL database and I am currently trying to get it to query the database for itmes LIKE the search query.
<?php
include ('connection.php');
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$sql = "SELECT * FROM entries WHERE name LIKE :searchq or description LIKE :searchq or content LIKE :searchq";
global $conn;
$stmt = $conn->prepare($sql);
$stmt->bindParam(":searchq",$searchq,PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
if($count == 0) {
$output = 'No results found, buddy.';
} else {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$elvl = $row['level'];
$ehp = $row['hp'];
$output .= '<tr><td>'.$eName.'</td><td>'.$eDesc.'</td><td>'.$elvl.'</td><td>'.$ehp.'</td></tr>';
}
}
return $output;
}
}
?>
I am struggling to get it to search. Unless the query exactly matches only the name, it doesn't show any results.
The LIKE operator does not do partial matches unless specifically instructed to. Perhaps you meant to prepend/append a % wildcard symbol to the search string:
$searchq = '%' . $searchq . '%';
I don't see anything wrong in the SQL text of the query.
The simplest explanation is that the SQL you are expecting to be sent to the database isn't what is being sent.
I suggest you give this a try:
use unique bind variable names in the statement, use each bind variable only once.
There used to be a bug in PDO with named bind variables (not sure if that's fixed of not. Under the covers, the named bind parameters were getting converted to positional notation, and when the same bind variable two or more times, the query being sent to MySQL wasn't what we expected.
For example:
$sql = "SELECT e.*
FROM entries e
WHERE e.name LIKE :searchq1
OR e.description LIKE :searchq2
OR e.content LIKE :searchq3";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":searchq1",$searchq,PDO::PARAM_STR);
$stmt->bindParam(":searchq2",$searchq,PDO::PARAM_STR);
$stmt->bindParam(":searchq3",$searchq,PDO::PARAM_STR);
When we encountered the problem, we weren't using server side prepared statements, just regular client side prepares; the SQL sent to the server included literals, not placeholders. Turning on the general_log in MySQL allowed us to see the actual SQL statements that were being sent to the database.
You might be encountering the same problem. But I'd recommend this as a step in debugging the problem, at least to verify it isn't the problem.
I need to get 'groupLeader' field from the table 'groups' in the database and store it in a variable and then compare to the current logged in username but I get the error:
Warning: mysql_numrows() expects parameter 1 to be resource, object given in /home/content/00/7923300/html/uber/tasks.php on line 31
The code I currently have is this:
$sq = "SELECT * FROM groups WHERE groupID='".$groupID."'";
$result=$db->query($sq);
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$gLeader= mysql_result($result, $i, 'groupLeader');
$i++;
}
if($_COOKIE['$username'] == $gLeader) {
echo "User is leader.";
}
Forgive me if this seems like a rather simple request. I'm new to php and working with databases.
EDIT: Forgot to mention line 31 is the line that contains
$num=mysql_numrows($result);
You might need to use with PHP's mysql_query or your framework row number method.
$result = mysql_query($sq);
Or perhaps
$db->number_of_rows($sq);
The problem here is, the query is not executed properly for an unknown reason. That is why it is returning False to $result, which is really not a resource.
use:
$sq = "SELECT * FROM groups WHERE groupID='".$groupID."'";
$result = mysqli_query($connection, $sq);
or
$result = mysql_query($sq);
Most of that code is redundant and pointless. if all you want is a single field from a single row, then don't do SELECT *, and don't use a loop.
$sql = "SELECT groupLeader FROM ..."
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($reuslt);
if ($row['groupLeader'] == $_COOKIE['username']) {
...
}
}
However, note that the mysql_*() function complex is officially deprecated in PHP and should not be used anymore. Consider switching to mysqli instead, which is generally drop-in compatible, or better yet, use PDO instead.
I am trying to select a table within my database with a GET Method.
Now when I hardcode the value of the variable in there (the table name) it works as expected and it returns the values in an array.
But when I try to determine the table name through a variable, I get the following error:
Fatal error: Call to a member function fetch_array() on a non-object in
Now I have tried the var_dump($result); but that returns bool(false).
Now the variable does carry a value, because when I echo it back to the screen it gives the value I would expect.
So why does not return the value when making the query for my table search???
$result = $mysqli->query("SELECT * FROM PodcastSermons WHERE sermonSeries = ". $series); //This where a change needs to happen
var_dump($result);
$posts = array();
while($row = $result->fetch_array())
{
$ID=$row['ID'];
$sermonTitle=$row['sermonTitle'];
$sermonSpeaker=$row['sermonSpeaker'];
$sermonSeries=$row['sermonSeries'];
$sermonDate=$row['sermonDate'];
$linkToImage=$row['linkToImage'];
$linkToAudioFile=$row['linkToAudioFile'];
$posts []= array (
'ID'=> $ID,
'sermonTitle'=> $sermonTitle,
'sermonSpeaker'=> $sermonSpeaker,
'sermonSeries'=> $sermonSeries,
'sermonDate'=> $sermonDate,
'linkToImage'=> $linkToImage,
'linkToAudioFile'=> $linkToAudioFile
);
}
$response['posts'] = $posts;
var_dump($posts);
PS I have read about the depreciation in mysql style and that I know have to use mysqli writing. I am running PHP Version 5.2.6-1+lenny16
If the $series is a string you need to put quotes around the variable..
Try...
$result = $mysqli->query("SELECT * FROM PodcastSermons WHERE sermonSeries = '". $series ."'");
Hope it helps.
Now I have tried the var_dump($result); but that returns bool(false).
Because your query failed.
Try:
if( ! $result = $mysqli->query("SELECT * FROM PodcastSermons WHERE sermonSeries = ". $series); ) {
echo "An error has occurred: \n" . var_export($mysqli->error_list, TRUE);
} else {
//do stuff
}
The central question seems to me: Where does $series come from? Where does that variable ever get initialized?
If you're passing this in from the web form, two things: either use $_GET or $_POST (whatever action you use in your form). And then you have to sanitize what comes from there, in order to not be vulnerable to SQL injection attacks. Prepared statements are your friend in this case; they help harden your script against this kind of attacks.
try this
$result = $mysqli->query("SELECT * FROM PodcastSermons WHERE sermonSeries = '$series' ");
$result = $mysqli->query("SELECT * FROM PodcastSermons WHERE sermonSeries = ". $series); //This where a change needs to happen
You should be using Prepared Statements if the variable: $series is user defined.
$result->prepare("SELECT * FROM PodcastSermons WHERE `sermonSeries`=?");
$result->bind_param('s', $series);
$result->execute();
Also, Print_r($result); to check if your initial $result to see if it has been populated; Furthermore, in your SQL Query is sermonSeries properly matched to your SQL Table?
Update:
while($row = $result->fetch_array())
{
Try Modifying this to:
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
http://uk1.php.net/manual/en/mysqli-result.fetch-array.php
your query simply fails. check var_dump($series); before executing.
i assume it might be a string and you just don't quote it?
just a tip: first build a string with your commandtext before
calling $mysqli->query. and use that string (like $mysqli->query($cmd);
dump that string :) might open your eyes ;)
that way you can extract it and execute it directly against the database (f.e. phpmyadmin).
I have a mySQL database from where I fetch some data via PHP.
This is what I've got:
if ($db_found) {
$URL_ID = $_GET["a"];
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = $URL_ID";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
$firstname = $db_field['firstname'];
$surname = $db_field['surname'];
$function = $db_field['function'];
$email = $db_field['email'];
$telnr = $db_field['telnr'];
}
mysql_close($db_handle);
}
else {
print "Database not found... please try again later.";
mysql_close($db_handle);
}
The URL_ID field in my mySQL database is, for this example, 001. When I go to www.mydomain.com/index.php?a=001 it fetches all the data, puts it into a variable, and I can echo the variables without any problem.
Now, I want to change the URL_ID, and I've changed it to "62ac1175" in the mySQL database. However, when I proceed to www.mydomain.com/index.php?a=62ac1175, I get this error message:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
boolean given in
mydomain.com\db_connect.php on line 17
The field in mySQL has varchar(8) as type and utf8_general_ci as collation.
If I change the entry back to 001 and change my URL to ?a=001, it works fine again.
What's going wrong?
You are not doing any error checking in your query, so it's no wonder it breaks if the query fails. How to add proper error checking is outlined in the manual on mysql_query() or in this reference question.
Example:
$result = mysql_query($SQL);
if (!$result)
{ trigger_error("mySQL error: ".mysql_error());
die(); }
your query is breaking because you aren't wrapping the input in quotes. You can avoid* quotes only for integers (which 62ac1175 is not). Try
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = '$URL_ID'";
Also, the code you show is vulnerable to SQL injection. Use the proper sanitation method of your library (like mysql_real_escape_string() for the classic mysql library that you are using), or switch to PDO and prepared statements.
In your code, this would look like so: Instead of
$URL_ID = $_GET["a"];
do
$URL_ID = mysql_real_escape_string($_GET["a"]);
* however, if you avoid quotes, mysql_real_escape_string() won't work and you need to check manually whether the parameter actually is an integer.
I am trying to access some information from mysql, but am getting the warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource for the second line of code below, any help would be much appreciated.
$musicfiles=getmusicfiles($records['m_id']);
$mus=mysql_fetch_assoc($musicfiles);
for($j=0;$j<2;$j++)
{
if(file_exists($mus['musicpath']))
{
echo ''.$mus['musicname'].'';
}
else
{
echo 'Hello world';
}
}
function getmusicfiles($m_id)
{
$music="select * from music WHERE itemid=".$s_id;
$result=getQuery($music,$l);
return $result;
}
Generally, the mysql_* functions are used as follows:
$id = 1234;
$query = 'SELECT name, genre FROM sometable WHERE id=' . $id;
// $query is a string with the MySQL query
$resource = mysql_query($query);
// $resource is a *MySQL result resource* - a mere link to the result set
while ($row = mysql_fetch_assoc($resource)) {
// $row is an associative array from the result set
print_r($row);
// do something with $row
}
If you pass something to mysql_fetch_assoc that is not a MySQL result resource (whether it's a string, an object, or a boolean), the function will complain that it doesn't know what to do with the parameter; which is exactly what you are seeing.
A common gotcha: you get this warning if you pass something (other than a valid query string) to mysql_query:
$id = null;
$query = 'SELECT name, genre FROM sometable WHERE id=' . $id;
$res = mysql_query($query);
// $res === FALSE because the query was invalid
// ( "SELECT name, genre FROM sometable WHERE id=" is not a valid query )
mysql_fetch_assoc($res);
// Warning: don't know what to do with FALSE, as it's not a MySQL result resource
Without seeing the code of getmusicfiles there's not a lot we can really help you with. You should be returning a valid mysql resource in that function.
As others have noted, you need to return a valid mysql resource into the mysql_fetch_assoc function to retrieve the next row. For example:
$sql = "select * from table";
$resultSet = mysql_query($sql) or die("Couldn't query the database.");
echo "Num Rows: " . mysql_num_rows($resultSet);
while ($resultRowArr = mysql_fetch_assoc($resultSet)) {
...
}
I think you need to specify what the function getQuery()
$result=getQuery($music,$l);
does
It depends on what exactly getmusicfiles() does. It must return a result of mysql_query() function call, then it will be a "valid MySQL result".
And you most probably wanted to put the line $mus=mysql_fetch_assoc($musicfiles) inside of the for cycle to fetch several rows one after another.
function getmusicfiles($m_id) {
$music="select * from music WHERE itemid=".$s_id;
$m_id != $s_id ?