If SQL returns no queries - php

I have this piece of code:
require_once('connectvars2.php'); //This is the connection to my database
$data = mysql_query("SELECT * FROM calzone ORDER BY id DESC");
if (isset($_POST['submit'])) {
$post = trim($_POST['post']);
$data = mysql_query("SELECT * FROM calzone WHERE overskrift LIKE '%$post%' OR postnummer = '$post'");
if (!(empty($data))) { // This is my poor attempt :-)
echo 'No result!';
}
}
This is my search function on my website.
I want it to return something if there is no queries which match the searchwords. Say if I write "6737" and the database finds no results, it should print "Sorry, but there's no results for your search!".
Is there a way for MySQL to check if there was returned any queries? and if not, echo some text?

Use mysql_num_rows
$data = mysql_query("SELECT * FROM calzone WHERE overskrift LIKE '%$post%' OR postnummer = '$post'");
if(mysql_num_rows($data) > 0){
//show your data
}
else{
echo "Sorry, but there are no results for your search!";
}
Also, as mentioned, mysql_query is deprecated. Switch to PDO.

Use mysql_num_rows function to count no. of rows..
$data = mysql_query("SELECT * FROM calzone WHERE overskrift LIKE '%$post%' OR postnummer = '$post'");
$num=mysql_num_rows($data);
if($num==0)
{
echo 'Sorry, but theres no results for your search';
}

require_once('connectvars2.php'); //This is the connection to my database
$data = mysql_query("SELECT * FROM calzone ORDER BY id DESC");
if (isset($_POST['submit'])) {
$post = trim($_POST['post']);
$data = mysql_query("SELECT * FROM calzone WHERE overskrift LIKE '%$post%' OR postnummer = '$post'");
if (mysql_num_rows($data) == 0){
echo "Sorry, but there's no results for your search!";
}else{
echo "matched";
}
}

use
if(mysql_num_rows($data)==0){
echo "Sorry, but there's no results for your search";
}

you are probably looking for mysql_num_rows
Use like this
$data = mysql_query("SELECT * FROM calzone WHERE overskrift LIKE '%$post%' OR postnummer = '$post'");
if (mysql_num_rows($data) == 0) {
echo 'No result!';
}
On a side note; you are using the mysql_XX functions to access the database. These have been replace with Mysqli and MySQL(PDO). Use one of these upto date libraries.

use mysql_num_rows($data)==0
Although you should use mysqli and not mysql as mysql is deprecated nowadays

First of all, you should not use mysql_-functions cause this PHP extension is deprecated. Try to use PDO or Mysqli extension instead.
By the way in this extension there is mysql_num_rows function which does exactly what you want.
$data = mysql_query("SELECT * FROM calzone WHERE overskrift LIKE '%$post%' OR postnummer = '$post'");
if (!mysql_num_rows($data)) {
echo 'No result!';
}

Use http://www.php.net/manual/en/function.mysql-num-rows.php
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";

Related

Get the number of rows

I need to get the number of rows of a studentID and then echo if the count is over 10.
This is what I wrote so far. But doesn't seem to work.
$findID = ID1231275;
$gipct = mysql_query("SELECT COUNT(studentID) FROM classFees WHERE studentID = '".$findID."'");
if ($gipct>10) {
echo ("$gipct");
}
$searchID = 'ID1231275';
$gipct = mysql_query("SELECT COUNT(studentID) as students FROM classFees WHERE studentID = '$searchID'");
$row = mysql_fetch_object($gipct);
if ($row->students >10) {
echo $row->students;
}
Btw, mysql_ functions are deprecated and can/will be removed in future versions of php, I recommend you to look at PDO statements or mysqli_ functions
$gipct is a mysql resource. So you have to use the function mysql_num_rows to get all rows that are selected.
Thats in your case not working because you have a COUNT in your query so you get only one row.
In your case you have to fetch the data first.
$gipct = mysql_query("SELECT COUNT(studentID) AS countout FROM classFees WHERE....");
$row = mysql_fetch_object($gpict);
if ($row->countout > 10) {
echo ("$gipct");
}
Or the method with the mysql_num_rows
$gipct = mysql_query("SELECT * FROM classFees WHERE student...");
if (mysql_num_rows($row) > 10) {
echo ("$gipct");
}
But here you select all records which can be much slower as the first solution.
If you are using php > 5 then you must use mysqli instead of mysql class. Then try this:
$db = new mysqli('localhost','user','pass','database');
$searchID = 'ID1231275';
$stmt = $db->prepare("SELECT COUNT(studentID) FROM classFees WHERE studentID =? ");
$stmt->bind_param('s', $searchID);
$stmt->execute();
$stmt->bind_result($gipct);
$stmt->fetch();
if ($gipct > 10) {
echo ($gipct);
}

Query not returning any results

I know that $wins should be 3. Because I have 3 rows with the integer "1" in the "win" column on table "rated_teams" But for some reason this code will not work. Can you find the problem please? ALSO, I'm aware that some of this is depracted. I'll update the whole page, once I get it at least in working condition.
<?php
$sql = "SELECT SUM(win) FROM rated_teams WHERE server='$server' AND name='$myteam'";
$query = mysql_query($sql, $con)
or die('A error occured: ' . mysql_error());
while ((mysql_fetch_array($query))) {
$wins = $row['SUM(win)'];
}
?>
<h3>Total Wins: <?php echo $wins?> </h3>
Try with
$sql = "SELECT SUM(win) as sum FROM rated_teams WHERE server='$server' AND name='$myteam'";
and while you are getting give like
while ($row = mysql_fetch_array($query)) {
$wins = $row['sum'];
}
And my advice is try to avoid mysql_* functions due to they are deprecated.Instead use mysqli_* functions or PDO statements.
You do not set the $row variable. Edit your while to this.
while ($row = mysql_fetch_array($query))
You need to give your calculated column an alias. Try this:
<?php
$sql = "SELECT SUM(win) as sumwin FROM rated_teams WHERE server='$server' AND name='$myteam'";
$query = mysql_query($sql, $con) or die('A error occured: ' . mysql_error());
while ($row = mysql_fetch_array($query)) {
$wins = $row['sumwin'];
}
?>
<h3>Total Wins: <?php echo $wins?> </h3>
Please write sql query right manner.Write like this.
$sql = "SELECT SUM(win) as sumwin FROM rated_teams WHERE server='".$server."' AND name='".$myteam."'";
while ((mysql_fetch_array($query))) {
should be
while ($row = mysql_fetch_array($query) ) {

search SQL for possibly duplicated user names using PHP

I want to search my database to see if a user that is registering is using a username that is currently in my database. I have registered the same name about 5 times so it SHOULD return false but it returns true.
<?php
function registerUser($userName, $userPassword) {
$db = new dbinterface();
$db->connect();
// check for duplicate data
$checkduplicates = "SELECT * FROM usersexample WHERE $userName = :userName";
$myresult = mysql_query($checkduplicates);
if(mysql_num_rows($myresult) > 0){
echo $myresult;
return false;
}
?>
My table name is usersexample and the field i am searching is userName.
ANY and ALL help is appreciated!
Using mysql_num_rows in examples i get this warning:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource.
Use mysql_num_rows() to check the number of rows returned.
Sample:
$myresult = mysql_query($checkduplicates);
$rowcount = mysql_num_rows($myresult);
if($rowcount > 0)
{
// Account name already in use
}
You should try this...
if(mysql_num_rows($myresult) > 0) {
echo $myresult;
return false;
}
It will return false if there is a duplicate username.
$getduplicates = mysql_query("SELECT * FROM table WHERE username = $username");
$duplicates = mysql_num_rows($getduplicates);
if($duplicates){
echo "Uh oh someone already has that username";
}
else {
echo "Everything is allllllll good";
}
Please use prepared statements to avoid sql injection.
As you are using :userName in your SQL it seems you are trying to do this (is your
database class based on PDO by any chance?). The :userName part will be replaced
by your variable $userName when you do the bindValue.
Use count() in the database to count the number of records found,
the database knows best ;-)
$query = $db->prepare("SELECT count(*) AS no_found FROM usersexample WHERE userName = :userName");
$query->bindValue(':userName', $userName, PDO::PARAM_STR);
$query->execute();
$result = $query->fetchObject();
if($result->no_found > 0)
{
return false;
}
Did you try:
$checkduplicates = "SELECT userName FROM usersexample
WHERE LOWER('".$userName."') = LOWER(userName)";
$myresult = mysql_query($checkduplicates)
if (!$myresult) {
die('Invalid query: ' . mysql_error());
} else {
$num_rows = mysql_num_rows($myresult);
if (!$num_rows) {
die('Invalid query: ' . mysql_error());
} else return ($num_rows == 0);
}
Please, sanitize user input to avoid SQL injection.
I don't know if you are doing something fancy I don't understand, but I would build the query like this:
$checkduplicates = "SELECT * FROM `usersexample` WHERE `userName` = '$userName'";
Or this
$checkduplicates = "SELECT * FROM `usersexample` WHERE `userName` = '".$userName."'";

Loop through array, query each value until certain condition is met

I'm a bit of a newb to PHP and MySQL. I seem to be having an issue with something. How do I loop through an array, querying each value in the array until the query meets a certain condition.. In this case it would be that the number of rows returned from the query is less than five. Here is what I have:
$query1="SELECT UserID FROM Users where RefID='$userid'";
$result1=mysql_query($query1);
while ($row = mysql_fetch_array($result1, MYSQL_NUM) && $sql2querynum < '5')
{
echo ($row[0]);
echo "
";
$sql2 = "SELECT * FROM Users WHERE RefID=$row[0]";
$sql2result = mysql_query($sql2);
$sql2querynum = mysql_numrows($sql2result);
}
Problem is, for every value it echoes out, I get the following warning:
mysql_numrows(): supplied argument is not a valid MySQL result resource
Like I said, I'm a newb, so maybe I'm not even going about doing this the right way.
try this
$query1="SELECT UserID FROM Users where RefID='$userid'";
$result1=mysql_query($query1);
if(mysql_num_rows($result1)<5)
{
while ($row = mysql_fetch_array($result1))
{
echo ($row[0]);
echo "
";
$sql2 = "SELECT * FROM Users WHERE RefID=$row[0]";
$sql2result = mysql_query($sql2);
$sql2querynum = mysql_numrows($sql2result);
}
}
$query1="SELECT UserID FROM Users where RefID='$userid'";
$result1=mysql_query($query1);
while ($row = mysql_fetch_array($result1, MYSQL_NUM) && $sql2querynum < '5')
{
echo ($row[0]);
echo "
";
$sql2 = "SELECT * FROM Users WHERE RefID={$row[0]}";
$sql2result = mysql_query($sql2);
$sql2querynum = mysql_numrows($sql2result);
}
Use { } for variables in " " ... and why you are not using joins ?

PHP MYSQL if null statement

I need a way to do this, If a mysql query dosn't retrieve any data, something happens. Here's an example.
$color="red";
$query = mysql_query("SELECT * FROM people WHERE shirt='$color'");
if($query = null){
echo 'No people wearing '.$color' shirts available.';
}
Use mysql_num_rows() for this.
if( mysql_num_rows($query) == 0 ) {
// No results returned
Use mysql_num_rows to check, how many rows have been returned by your query.
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
if( $num_rows == 0 ) {
// No results returned
echo "No results!";
} else {
echo "$num_rows Rows\n";
}
?>
Besides the mysql_num_rows() there is also COUNT() which could be used like this:
"SELECT COUNT(*) FROM people WHERE shirt='$color'"
You might actually need more data from the database but if you only need a number then this would remove the need for an if.
You could use empty either:
$num_rows = mysql_num_rows($result);
if(empty($num_rows)){
echo 'No results';
}

Categories