Issue with if statement variable [duplicate] - php

This question already has answers here:
The 3 different equals
(5 answers)
Closed 7 years ago.
I am trying to create this simple if statement, but I am running into issues with the variable $testnumrows. In this if condition I am trying to see if there are any group columns with data and if so echo the amount of rows, but I want nothing to show up if there isn't.
In my db I have 6 rows that have what I mentioned in the query. The output that is showing up on the page is 0 though, so it seems my variable is being reset.
Before I had this:
$testnumrows = mysqli_num_rows($test);
echo " " . $testnumrows;
and it read the 6, I just can't get the if statement to work.
Here is the full code now.
<?php
$con = mysqli_connect("localhost", "", "", "");
$test = mysqli_query($con,"SELECT `group` FROM user_requests WHERE `group` = 1");
$testnumrows = mysqli_num_rows($test);
if($testnumrows = 0) {
echo "";
} else {
echo " " . $testnumrows;
}
?>

It should read if($testnumrows == 0) {.

Trivial error = instead of ==
Solution:
if($testnumrows == 0) {
echo "";
} else {
echo " " . $testnumrows;
}

Change if($testnumrows = 0) to if($testnumrows == 0).

Related

Show alert message if MySQL php query match one condition [duplicate]

This question already has answers here:
How to pop an alert message box using PHP?
(9 answers)
Closed 1 year ago.
I have an online software that use php, html, js and MySQL as database.
I have two tables:
1- First table contains [name, imei, object_expire, object_expire_dt] - gs_objects
2- Second table contains [object_id, user_id, imei] - gs_user_objects
The code should be done in php where the user_id is got from the session, then the first query should get the imeis that matches the user_id from second table then it should get the expire date 'object_expire_dt' of each imei from the first table
after that it should check if there is an expire date that will expire within 20 days, if true, it should show alert message
Here is incomplete code that I tried to do
//notification for objects expiration
checkUserSession();
loadLanguage($_SESSION["language"], $_SESSION["units"]);
// check privileges
if ($_SESSION["privileges"] == 'subuser')
{
$user_id = $_SESSION["manager_id"];
}
else
{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM `gs_user_objects` WHERE `user_id`='".$user_id."' ORDER BY `object_id` ASC";
$r = mysqli_query($ms, $q);
while($row=mysqli_fetch_array($r))
{
$q2 = "SELECT * FROM `gs_objects` WHERE `imei`='".$row['imei']."' ORDER BY `object_id` ASC";
$r2 = mysqli_query($ms, $q2);
while($row=mysqli_fetch_array($r2))
{
$Date_e = date("Y-m-d");
if ( $row['object_expire_dt'] > date('Y-m-d', strtotime($Date_e. ' - 20 days')))
{
alert("You have objects are going to expire soon");
}
}
}
the code didn't work, I need some help in it.
Thanks in advance
Here's how all this works: Your php program runs on your server, and accesses your database on the server. The purpose of your php program is to create programs to run on your users' browsers. Those programs written by php use the HTML, Javascript, and CSS languages.
If you want something to happen in a user's browser (like an alert box) that thing has to appear in a Javascript program written by your php program and sent to the browser. php doesn't have its own alert() function
Here's an easy, but somewhat sloppy, way to do that in your php program.
echo "<script type='text/javascript'>window.onload=function(){alert('$msg'))</script>";
What's going on here?
echo tells php to write its parameter to the html page
<script> whatever </script> is the way to embed Javascript in html
window.onload = function () { whatever } tells the browser to run a Javascript function when your html page finishes loading.
alert(message), in the function, pops up the alert message.
When you're troubleshooting this kind of thing, View Source ... is your friend.
you can use alert in javascript not in php
also you should use prepared statement.
//notification for objects expiration
checkUserSession();
loadLanguage($_SESSION["language"], $_SESSION["units"]);
// check privileges
if ($_SESSION["privileges"] == 'subuser'){
$user_id = $_SESSION["manager_id"];
}else{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM gs_user_objects WHERE user_id = ? ORDER BY object_id ASC";
if ($r = $connection->prepare($q)) {
// if user_id contains string and is not integer you must use "s"
$r->bind_param("i",$user_id);
if ($r->execute()) {
$result = $r->get_result();
// check if result match one condition
if ($result->num_rows > 0) {
echo "result found";
while ($row = $result->fetch_assoc()) {
echo $row['some_column_name'];
}
}
}
}
Thanks Nikolaishvili and Jones,
Your answers helped me a lot I needed more edit on the if statements,
I did the code and the result is as I expected and it is online now, here the code is below so others can check it
//notification for objects expiration
// check privileges
if ($_SESSION["privileges"] == 'subuser')
{
$user_id = $_SESSION["manager_id"];
}
else
{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM `gs_user_objects` WHERE `user_id`='".$user_id."' ORDER BY `object_id` ASC";
$r = mysqli_query($ms, $q);
$expiry_flag = 0;
$inactive_flag=0;
while($row=mysqli_fetch_array($r))
{
$q2 = "SELECT * FROM `gs_objects` WHERE `imei`='".$row['imei']."'";
$r2 = mysqli_query($ms, $q2);
while($row2=mysqli_fetch_array($r2))
{
$Date_e = date("Y-m-d");
if ( $row2['object_expire_dt'] < date('Y-m-d', strtotime($Date_e. ' + 20 days')))
{
if ($row2['object_expire_dt'] > '0000-00-00')
{
$expiry_flag = 1;
}
}
if ( $row2['object_expire_dt'] < date("Y-m-d"))
{
if ($row2['object_expire_dt'] > '0000-00-00')
{
$inactive_flag = 1;
}
}
}
}
if ($expiry_flag == 1)
{
echo '<script type="text/javascript">';
echo ' alert("my msg1")';
echo '</script>';
}
if ($inactive_flag == 1)
{
echo '<script type="text/javascript">';
echo ' alert("my msg2")';
echo '</script>';
}
Thanks

Echo images using php according to a particular condition [duplicate]

This question already has an answer here:
echo image according to a condition
(1 answer)
Closed 6 years ago.
I have this query :
$q4 = "SELECT TOP 5 b.BadgeName, b.BadgeImage FROM BadgeImageTable AS b
INNER JOIN employee_badge AS e
ON e.badge_id = b.BadgeID
WHERE e.employee_id = 2164
ORDER BY e.earned_on DESC ";
$stmt3=sqlsrv_query($conn,$q4);
if($stmt3==false)
{
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors(),TRUE));
}
the query returns this :
Now in my php, i am trying to echo any three random images from the 'BadgeImage' column,if the query gives more than 3 rows of data.Else,if the query gives 2 rows,display only 2 images,if 1 row,display only 1 'badgeImage' and so on.
PHP Code that I tried and which is not giving the correct result :
<div class="badgesize">
<?php
if($count = sqlsrv_num_rows($stmt3) > 0){
while($recentBadge = sqlsrv_fetch_array($stmt3)){
$result[] = $recentBadge;
}
if($count > 3){
foreach(array_rand($result, 3) as $val){
$data[] = $result[$val];
}
$result = $data;
}
foreach($result as $recentBadge){
echo $recentBadge['BadgeName'], '<img src="'.$badgerecent['BadgeImage'].'">';
}
} else {
echo 'no results';
}
?>
</div>
When I run the above PHP it is giving 'no result' inh the UI i.e "it is not running the if statement' and directly going to the else part of the PHP.
This shouldnot happen as the query fetches 5 rows of data as shown in above picture.
When I try to echo simply (using below code) without the above condition,I am able to do so without any issue.
<img src="<?php echo "".($recentBadge['BadgeImage']).""; ?>" >
I am using PHP 5.5.38 and sql server 2012
Change the following:
if($count = sqlsrv_num_rows($stmt3) > 0){
to
$count = sqlsrv_num_rows($stmt3); // getting the record count
if($count > 0){ // checking if there is some rows present or not
while($recentBadge = sqlsrv_fetch_array($stmt3)){
// your code
}
}
and one more thing do not put full path of the image in badgeImage column as this will create problem when you move code from local to server. Keep only path of image folder and image name.
Apparently sqlsrv_num_rows() does not return an expected result which is explained here
Alternatively you can use that fix or you can use the following code:
if(sqlsrv_has_rows($stmt3)){
while( $row = sqlsrv_fetch_array($stmt3, SQLSRV_FETCH_ASSOC) ) {
$recentBadge[] = $row;
}
if(count($recentBadge) > 3){
foreach(array_rand($recentBadge, 3) as $key){
$data[] = $recentBadge[$key];
}
$recentBadge = $data;
}
} else {
$recentBadge = [];
}
foreach($result as $recentBadge){
echo $recentBadge['BadgeName'], '<img src="'.$badgerecent['BadgeImage'].'">';
}
This way we're checking if there are found rows instead, is so, store them all in an array and count the size of the array instead.
replace
if($count = sqlsrv_num_rows($stmt3) > 0){
with
$count = sqlsrv_num_rows($stmt3);
if($count > 0){

zero not disappearing [duplicate]

This question already has answers here:
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 8 years ago.
$i=0;
$sql = $dbh->prepare('SELECT kappaleen_nimi, levy_id, kesto FROM kappaleet');
$ok = $sql->execute();
if(!$ok) { print_r( $sql->errorInfo() ) ; }
while($row = $sql->fetch(PDO::FETCH_ASSOC) ) {
foreach($row as $value) {
if($value!=null || $value!=0){
$haku2[$i] = $value;
$i=$i+1;
}
}
}
I'm working with this sql database, where i'm fetching kappaleen_nimi (name of the track), levy_id (record_id) and kesto (length) from the sql table kappaleet. I'm trying to remove fields containing null or 0. However, the final zero gets through anyway through this filter: "if($value!=null || $value!=0)".
When printing my table the following way:
foreach($haku2 as $value){
echo $value.', ';
}
I get this kind of result (last few fields): "Sateen tango, 7, 3.11, 0, "
The final zero is still there, and i can't get my head around it, why the he** it passes the if condition... I know that the final zero is levy_id (record_id).
I think you are looking for an AND conditional instead of an OR. To fix this, replace the following line
if($value!=null || $value!=0){
with this one
if($value!=null && $value!=0){

PHP Ajax return more than one row from database [duplicate]

This question already has answers here:
How do I loop through a PHP array containing data returned from MySQL?
(6 answers)
Closed 8 years ago.
I wrote some PHP and Ajax code in order to see my inventory when I type in a location name. Here is an image of my inventory. Notice most of the locations contain more than one kind of items.
And here is the front end interface I have.
Here's the part of the code I have problems with.
<?php
// '.post' could be '.get' here but global.js has to be the same, .post is faster
if(isset($_POST['name']) === true && empty($_POST['name']) === false) {
require '../db/connect.php';
$query = mysql_query("
SELECT `sheet0_100`.`id`
FROM `sheet0_100`
WHERE `sheet0_100`.`location` = '" . mysql_real_escape_string(trim($_POST['name'])) . "'
");
echo (mysql_num_rows($query) !== 0) ? mysql_fetch_row($query) : 'Location not found..';
}
?>
If you notice mysql_fetch_row part, when I type in a location, for instance, 50A-3, it returns a word "Array" instead of the record. Same result for those locations have more than one rows. I wonder what do I have to do with $query so that the webpage can display all the rows from a location? Thanks!
If you must use the mysql_* extension functions, in order to retrieve and therefor display multiple rows, use a while loop:
<?php
// '.post' could be '.get' here but global.js has to be the same, .post is faster
if(isset($_POST['name']) === true && empty($_POST['name']) === false) {
require '../db/connect.php';
$query = mysql_query("
SELECT `sheet0_100`.`id`
FROM `sheet0_100`
WHERE `sheet0_100`.`location` = '" . mysql_real_escape_string(trim($_POST['name'])) . "'
");
if(mysql_num_rows($query) !== 0){
while ($row = mysql_fetch_row($query)) {
// output results using the $row array
}
}
else {
echo('Location not found..');
};
}
?>
mysql_fetch_row fetches each row one at a time

How to do something different for the last item in an array (from mysql_fetch_array)? [duplicate]

This question already has answers here:
Echo a comma on all but the last value? (result from mysql_fetch_array)
(11 answers)
Why doesn't it prevent further looping?
(2 answers)
Closed 8 years ago.
I am trying to make sure that commas go after all of the items EXCEPT for the last one - I am trying to figure out how to calculate out what the last item is for variable lists. I decided to try to use count($variablename) but it doesn't seem to work.
Is there something wrong with my syntax?
$servicearray = mysql_query("select serv_id from org_serv_xref where org_id='".$org_id."'");
$servi = 0;
while ($servicearrayrow = mysql_fetch_array($servicearray)) {
$servdescarray = mysql_query("select serv_desc from service where serv_id='".$servicearrayrow['serv_id']."'");
while ($servdescarrayrow = mysql_fetch_array($servdescarray)) {
if ($servi < 5 OR $servi < count($servdescarrayrow)) {
ECHO $servdescarrayrow['serv_desc'].",";
$servi++;
}
else if ($servi == 5 OR $servi == count($servdescarrayrow)) {
echo $servdescarrayrow['serv_desc'];
$servi++;
}
else {
$servi = 0;
break 2;
}
}
}
Because you're starting $servi at 0. It will always be less than the count of the array. If you start it at 1 it should work the way you expect it to.
change your query to
$servicearray = mysql_query("select GROUP_CONCAT(serv_id) from org_serv_xref where org_id='".$org_id."'");
now sql builds the nice comma delimited list for you :)
As near as I can figure, your trying to do something like this (although I could be totally wrong):
// Initialise vars
$lastid = '';
$items = array();
// Do the query
$query = "SELECT serv_desc, serv_id
FROM service
WHERE serv_id IN (
SELECT serv_id
FROM org_serv_xref
WHERE org_id='".$org_id."'
)
ORDER BY serv_id";
$servdescarray = mysql_query($query);
while ($servdescarrayrow = mysql_fetch_assoc($servdescarray)) {
// We've reached the next ID, echo the result of the last one.
if ($lastid != $servdescarrayrow['serv_id']) {
$lastid = $servdescarrayrow['serv_id'];
if (count($items)) {
echo implode(',',$items);
$items = array();
}
}
if (count($items) == 5) { // We don't want more than 5 items
continue;
} else { // Add an item to the results
$items[$servdescarrayrow['serv_desc']];
}
}
// Make sure we get the last one
if (count($items)) {
echo implode(',',$items);
}

Categories