I have a variable called $uid, and I would like to print a message if the variable $uid is not contained in the "loginid" field of a MySQL table "tweets" on any row that has another variable, $submissionid. I think my query $tweetquery is okay. Basically, I would like the message to echo if the loginid variables pulled from "tweets" never equal $uid.
How can I do this?
Thanks in advance,
John
$tweetquery = "SELECT loginid
FROM tweets
WHERE submissionid = '$submissionid'";
$tweetresult = mysql_query($tweetquery);
if...
echo '<div>Message</div>';
Have a look at mysql_num_rows($result).
if ( mysql_num_rows($result) > 0 )
{
// Do something
}
else
{
echo 'No results';
}
Call me crazy, but using mysql_num_rows is not the way I'd do this. mysql_fetch_array does not do anything destructive if nothing is returned, so call that as normal.
$row = mysql_fetch_array( $resource );
if(!$row)
{
//do what you would do if the query returned nothing
}
else
{
do
{
// do what you would do with the row
} while( $row = mysql_fetch_array( $resource ) );
}
The problem with mysql_num_rows is that it actually represents a call to the database asking for how many rows exist in the pointer. It is a, frankly, needless back-and-forth which can easily be avoided. So why not avoid it?
You can use mysql_num_rows:
if (mysql_num_rows($tweetresult) > 0)
// results found
Use mysql_num_rows():
if (mysql_num_rows($tweetresult) == 0) {
echo 'Message';
}
if(mysql_num_rows($tweetresult) == 0)
echo "<div>Message</div>";
else {
//Do something if $uid was found
}
mysql_num_rows() returns the numbers of rows fetched from the database. If rows fetched are zero echo a message.
$tweetquery = "SELECT loginid
FROM tweets
WHERE submissionid = '$submissionid'";
$tweetresult = mysql_query($tweetquery);
if(mysql_num_rows($tweetresult) > 0){
// your results here
} else {
echo '<div>Message</div>';
}
Related
I try to get the value 'entryScans' from my SQL-table and send it to $output based on the IF-ELSE case. What am I doing wrong?
<?php
include ('config.php');
$TicketNo=$_POST["TicketNo"];
$hash=$_POST["hash"];
$sql = "SELECT TicketNo,hash,entryScans FROM `Tickets` WHERE `TicketNo` = '$TicketNo' AND `hash` = '$hash'" or die(mysql_error());
$result = mysql_query($sql);
$row=mysql_num_rows($result);
if($row['entryScans'] = 0){
$output="ok";
}
else if ($row['entryScans'] > 0) {
$output="maybe";
else{
$output="error";
}
print(json_encode($output));
mysql_close();
?>
You are doing ...
if($row['entryScans'] = 0){
Which has 2 problems, = is assignement, == is testing equal to. The second part is that your fetching the results in...
$result = mysql_query($sql);
$row=mysql_num_rows($result);
So $row is the number of rows, $result is the query results...
So to check the number of rows in the result set
if($row == 0){
etc.
Update:
If you want the value of the column entryScans to be used, then you need to change the call of mysql_num_rows() to mysql_fetch_assoc(), so
$row=mysql_fetch_assoc($result);
Then you can leave the rest of the code to use $row['entryScans']
You are not processing your results. You just get the total number of rows in $row variable.
You need to process your query result by looping method.
Here is the example
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
if($row['entryScans'] = 0)
{
$output="ok";
}
else if ($row['entryScans'] > 0)
{
$output="maybe";
}
else
{
$output="error";
}
}
Hope this works for you.
This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 5 years ago.
Ok so basically I'm trying to create a simple web app
I want to check if one element is inside the table, and if inside I want to return a boolean value, like for example if "abc" is inside the table named "name" then return YES.
Here's my code, not working:
error_reporting(E_ALL);
$mysql = mysqli_connect(/* PRIVATE DATA */) or die ("ERROR CONNECTING TO THE DB");
if(isset($_POST['submit'])) {
$theAddress = $_POST['youtubeURL'];
$result = "SELECT * FROM data WHERE youtubeURL = '" . $theAddress . "'";
$query = mysqli_query($mysql, $result);
if (!$query) {
printf("Error");
} else {
printf("NO ERROR");
}
AND HERE'S THE NON-WORKING PART :
while($row = mysqli_fetch_array($query)) {
if ($row == 0) {
echo "NO RESULT LIKE THIS";
}else {
echo "AT LEAST ONE RESULT LIKE THIS";
}
}
}
First, learn to use parameters queries. They really are no harder to use than stuffing a string value into a query.
Second, if you want to know if something exists, then write the query just to do that. The simplest query is probably:
SELECT EXISTS (SELECT 1 FROM data WHERE youtubeURL = ?) as exists_flag
This will return 1 if something matches. Just run the query and read the single value that is returned.
Note that returning select * to check for existence is an anti-pattern. You are returning way more data from the database than you need (both in terms of rows and columns). That is usually not a good idea.
It should be like this.
//in case you want to see total of the wors
if(mysqli_num_rows($query) == 0) {
echo "NO RESULT LIKE THIS";
} else {
echo "AT LEAST ONE RESULT LIKE THIS";
}
//in case you want to check for each of the row
while($row = mysqli_fetch_array($query)) {
if (empty($row)) {
echo "NO RESULT LIKE THIS";
} else {
echo "AT LEAST ONE RESULT LIKE THIS";
}
}
You need to use mysqli_num_rows to count the rows ..
$result = "SELECT * FROM data WHERE youtubeURL = '" . $theAddress . "'";
$query = mysqli_query($mysql, $result);
if(mysqli_num_rows($query)) {
echo "AT LEAST ONE RESULT LIKE THIS";
} else {
echo "NO RESULT LIKE THIS";
}
please take a look at this code :
$sql = "SELECT * FROM shop";
$result = mysql_query($sql);
echo $result;
echo "before lop";
while ($xxx = mysql_fetch_assoc($result)) {
echo "inside lop";
echo $xxx['column_name'];
}
echo "after lop";
When I run such code i receive :
Resource id #244
before lop
after lop
It did not enter while lop, and I really don't know why :(
I used before such code and there were no problems.
Can someone help me?
$sql = "SELECT * FROM shop";
$result = mysql_query($sql) or die(mysql_error());
echo mysql_num_rows($result);
Check how many records are present in your shop table. I think shop table is empty.That is why not entering in the while loop.
You can do like this
$count = mysql_num_rows($result);
if($count > 0) {
while ($xxx = mysql_fetch_assoc($result)) {
echo $xxx['column_name'];
}
}
I would guess that the call to mysql_fetch_assoc() has returned false, possibly due to no results being returned from the database, this would cause the while loop to not execute even once. I would check the output of var_dump(mysql_fetch_assoc($result)) to ensure that data has been returned.
I have made a simple MySQL query search in one of my PHP site, but it doesn't work as I expect. When user search a term in my search bar, if the content he/she looking for doesn't exist, my function should return 'no results'. but it just display blank, no message nothing.
Here is my code for the search:
function querySearch($searchTerm) {
$query = "SELECT * FROM content_en WHERE content_body LIKE '%{$searchTerm}%' ORDER BY id DESC ";
return $query;
}
function getSearch($searchTerm) {
$queryContents= querySearch($searchTerm);
$exeQuery = mysql_query($queryContents);
while( $fetchSet = mysql_fetch_array($exeQuery) ){
if(empty($fetchSet)){
echo "No Results Found";
}else{
if(empty($fetchSet['content_title'])){
echo 'Sorry No results Found';
}else{
echo '<h2>'.$fetchSet['content_title'].'</h2><br/>';
echo '<div>'.shortText($fetchSet['content_body'], 220).'</div><br/><br/>';
}
}
}
}
Just my forcing it to work , so that's why there are two check for fetchSet array one for whole array one for only one key. But yea it doesn't work.
The reason it's not working is because there is either an error in your query or it has returned no results.
First, you should add some sort of error handling to your mysql_query, like this:
$exeQuery = mysql_query($queryContents) or die(mysql_error());
Second, the reason it would never print anything out if no results are found is because mysql_fetch_array will only loop over the results if there is a result to obtain. Therefore, if 0 rows are returned, the whole while loop is skipped completely. Instead you can use mysql_num_rows BEFORE you loop.
For example:
if (mysql_num_rows($exeQuery) > 0) {
while( $fetchSet = mysql_fetch_array($exeQuery) ){
echo '<h2>'.$fetchSet['content_title'].'</h2><br/>';
echo '<div>'.shortText($fetchSet['content_body'], 220).'</div><br/><br/>';
}
}
else {
echo "No Results Found";
}
Try this code
function querySearch($searchTerm) {
$query = "SELECT * FROM content_en WHERE content_body LIKE '%{$searchTerm}%' ORDER BY id DESC ";
return $query;
}
function getSearch($searchTerm) {
$queryContents = querySearch($searchTerm);
$exeQuery = mysql_query($queryContents);
if(mysql_num_rows($exeQuery) > 0)
{
while( $fetchSet = mysql_fetch_array($exeQuery) )
{
echo '<h2>'.$fetchSet['content_title'].'</h2><br/>';
echo '<div>'.shortText($fetchSet['content_body'], 220).'</div><br/><br/>';
}
}
else
{
echo "No Results Found";
}
}
I'm not 100% sure about this, but I do recall that mysql_fetch_array will work only if there are actual results fetched. The while loop will only run when the mysql_fetch_array function runs successfully. However, when the query returns no results, mysql_fetch_array will not run successfully, so the loop will not run, thus, your if block is not given the opportunity to run either.
Edit: Habeeb's code should fix your problem for you :p. Keeping my answer here though, since I do provide some explanation as to the problem with your code. I'm sure it will be a useful reference to someone who might look at this in the future.
Try This one..
function querySearch($searchTerm) {
$query = "SELECT * FROM content_en WHERE content_body LIKE '%{$searchTerm}%' ORDER BY id DESC";
return $query;
}
function getSearch($searchTerm) {
$queryContents= querySearch($searchTerm);
$exeQuery = mysql_query($queryContents);
$num_rows = mysql_num_rows($exeQuery);
if($num_rows)
{
while( $fetchSet = mysql_fetch_array($exeQuery) ){
echo '<h2>'.$fetchSet['content_title'].'</h2><br/>';
echo '<div>'.shortText($fetchSet['content_body'], 220).'</div><br/><br/>';
}
}else{
echo "No Result Found!";
}
}
I have a query $sqlStr4 that "selects" these fields from a MySQL database:
loginid
username
created
The query $sqlStr4 is limited to 10 rows / results.
I also have the following variable:
$u = $_SESSION['username'];
I would like to assign another variable $topten a value of 1 if $u equals any of the ten username fields returned by the query $sqlStr4, and a value of 0 if it does not.
How can I do this?
Thanks in advance,
John
Use:
<?php
$u = $_SESSION['username'];
$topten = 0;
$result = mysql_query($sqlStr4);
while ($row = mysql_fetch_assoc($result)) {
if ($row['username'] == $u) {
$topten = 1;
break;
}
}
mysql_free_result($result);
?>
If you had pasted the query, we'd be able to provide a fixed version. You can do this multiple ways, but one would be to add a column to your query and use a CASE statement.
select *, CASE WHEN username = '$u' THEN 1 ELSE 0 END as topten
from ...
This is just an example.. obviously to prevent SQL injection you should parameterize it, or use mysql_real_escape_string(), or a stored procedure, etc etc...
EDIT: I see you want the variable to be in PHP... so you would need to loop through the array to check each one. What is the problem you're having?...
$topten = 0;
if ($result) {
while ($record = mysql_fetch_array($result)) {
if ($record['username'] == $u) $topten = 1;
}
}
Could try something like this...
while ($row = mysql_fetch_assoc($sqlStr4))
{
$topten = ($u == $row['username']) ? 1 : 0;
// the rest of your processing code here
}
There may well be better solutions for your situation. Would be easier if you posted some code!