Alternate to mysqli_num_rows for this php script - php

I know this has been asked a lot but I can't find no other method that does not relate to num_rows I basically want to see if a record a exist in the database in a if else statement and in other words I don't mind using it but for personal complicated reasons I need to stay away from that because it conflicts on other things I want to add down the road. So this is my code example is there another way to do this with out using mysqli_num_rows?
<?php
$servername='localhost';
$username='angel';
$password='1234';
$db_name='test';
$connect= new mysqli($servername,$username,$password,$db_name);
$query="SELECT*FROM members WHERE first_name='bob'";
$result= $connect->query($query);
if($result->num_rows >0){
echo 'Exist';
}
else{
echo 'Does not exist';
}
?>

just to fill in the options pool
$query = "SELECT id FROM members WHERE first_name='bob'";
then check you get an id returned; assuming the table has an id column, if not just use another one

You could issue a separate query where all you do is count the results:
$getCount = "SELECT COUNT(*) AS `MemberCount` FROM members WHERE first_name='bob'";
Then use the results to determine your program's path.

Related

Check if value is found in SQL table within PHP script?

I need to be able to check and see in a certain string is anywhere within my SQL table. The table I am using only has one column of char's. Right now it is saying that everything entered is already within the table, even when it actually is not.
Within SQL I am getting the rows that have the word using this:
SELECT * FROM ADDRESSES WHERE STREET LIKE '%streeetName%';
However, in PHP the word is being entered by the user, and then I am storing it as a variable, and then trying to figure out a way to see if that variable is somewhere within the table.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one of each address allowed.<br /><hr>";
}
You need to do a little bit more than building the query, as mysql_query only returns the resource, which doesn't give you any information about the actual result. Using something like mysql_num_rows should work.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(mysql_num_rows($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
Note: the mysql_* functions are deprecated and even removed in PHP 7. You should use PDO instead.
In the SQL you used
%streeetName%
But in the query string below, you used
%$streeetName%
Change the correct one
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
if($results->num_rows) is what you need to check if you have results back from your query. An example of connection and query, check, then print or error handle, the code is loose and not checked for errors. Best of luck...
//Typically your db connect will come from an includes and/or class User...
$db = new mysqli('localhost','user','pass','database');
$sql = "SELECT * FROM `addresses` WHERE `street_name` LIKE '%$streetName%'",$connect;
//test your queries in PHPMyAdmin SQL to make sure they are properly configured.
//store the results of your query in a variable
$results = $db->query($sql);
$stmt = '';//empty variable to hold the values of the query as it runs through the while loop
###########################################################
#check to see if you received results back from your query#
###########################################################
if($results->num_rows){
//loop through your results and echo or assign the values as needed
while($row = $results->fetch_assoc()){
echo "Street Name: ".$row['STREET_NAME'];
//define more variables from your DB query using the $row[] array.
//concatenate values to a variable for printing in your choice further down the document.
$address .= $row['STREET_NAME'].' '.$row['CITY'].' '$row['STATE'].' '$row['ZIP'];
}
}else{ ERROR HANDLING }

mysqli query in WHILE loop

1.) Can you nest a msqli_query inside a while loop?
2.) If yes, why would the PHP below not write any data to the precords table?
If I echo a $build array variable it shows properly, but the mysqli insert writes nothing to the table in the DB. THe code does not error out anywhere, so what am I missing about this?
$data = mysqli_query($con,"SELECT * FROM Cart WHERE Buyer_ID='$_SESSION[cid]' AND Cart_Date='$_SESSION[cdate]'");
while($build = mysqli_fetch_array($data))
{
//echo $build[idex]."<br>";
mysqli_query($con,"INSERT INTO precords (precord,Buyer_ID,Account,Purchase_Date,Item_Number,Item_Qty,Item_Title,Item_FPrice,Item_FFLFlag,ccpass) VALUES ('$build[idex]','$build[Buyer_ID]','$build[Cart_Date]','$build[Item_Number]','$build[Item_Qty]','$build[Item_Title]','$build[Item_FPrice]','$build[Item_FFLFlag]','N')");
};
Thanks for any help.
** P.S. - This code is meant to move certain values from a TEMPORARY table/session variables, over to a permanent record table, but the loop is needed since there is more than one product in the cart associated with the user/session.
yes you can use it in a loop and
you may wanna add mysql_error() function to find out what's wrong with it and try to fix it or by adding the error to the question so we can tell you what to do
$data = mysqli_query($con,"SELECT * FROM Cart WHERE Buyer_ID='$_SESSION[cid]' AND Cart_Date='$_SESSION[cdate]'");
while($build = mysqli_fetch_array($data))
{
// echo $build[idex]."<br>";
mysqli_query($con,"INSERT INTO precords(precord,Buyer_ID,Account,Purchase_Date,Item_Number,Item_Qty,Item_Title,Item_FPrice,Item_FFLFlag,ccpass)
VALUES ('$build[idex]','$build[Buyer_ID]','$build[Cart_Date]','$build[Item_Number]','$build[Item_Qty]','$build[Item_Title]','$build[Item_FPrice]','$build[Item_FFLFlag]','N')")
or die (mysql_error());
};
in a simplified form when you want to fetch data from a database to display in html list I intentionally added mysqli ORDER BY which have only two order ASC[ascending] and DESC[descending] and I also used mysqli LIMIT which i set to 3 meaning that number of result fetch from the database should be three rows only
I concur with the answer of ali alomoulim
https://stackoverflow.com/users/2572853/ali-almoullim
MY SIMPLIFIED CODE FOR THE LOOPING WHILE MYSQLI ORDER BY AND LIMIT
$usersQuery = "SELECT * FROM account ORDER BY acc_id DESC LIMIT 3";
$usersResult=mysqli_query($connect,$usersQuery);
while($rowUser = mysqli_fetch_array($usersResult)){
echo $rowUser["acc_fullname"];
}

mysql - strange thing with update and select statements

I have a strange mysql-thing going on here, it is about the following code:
$res = mysql_query("SELECT * FROM users WHERE group='".$group."'");
if (mysql_num_rows($res)==1) {
$row = mysql_fetch_assoc($res);
$uid = $row['uid'];
$user_update = mysql_query("UPDATE fe_users SET group = 5 WHERE group='".$group."'");
return 'ok';
} else {
return 'not ok';
}
I am checking, if there is a user with the group = $group. If so, the group is updated to 5 and after that the string "ok" is returned, if no user with group=$group exists, as you can see the string "not ok" is returned.
This should be very easy, but the problem now is, that if there is a user with group=$group, the update is done correctly, but instead of returning "ok", php returns "not ok", as if the change from the update is been taken into account for the above executed select retroactively. I dont understand this. Any help would be really appreciated.
Thanx in advance,
Jayden
I think 'group' is a reserved keyword that you have used as a field name, change it or use like
$res = mysql_query("SELECT * FROM users WHERE `group`='".$group."'");
and
$user_update = mysql_query("UPDATE fe_users SET `group` = 5 WHERE `group`='".$group."'");
and you can use count($res)==1 instead of mysql_num_rows($res)==1 if it is a problem.
Reference: Mysql Reserved keywords.
I am not sure if this has any merit but try using this style in your SELECT and UPDATE commands: WHERE group='$group', without using string joins. Other than that I can't seem to see why you are getting an update and not being returned "ok".
You are checking if mysql_num_rows($res)==1, so you'll return ok if there is exactly one user on that group. If there are two or more users, it will return not ok. Probably not what you want, right? I think you should check if mysql_num_rows($res)>=1.
You might consider modifying the placement of your brackets, and changing your num_rows check, like so:
$res = mysqli_query("SELECT uid FROM users WHERE `group` ='".$group."'");
if (mysqli_num_rows($res)>0) {//there was a result
while($row = mysqli_fetch_assoc($res)){
// grab the user id from the row
$uid = $row['uid'];
// and update their record
$user_update = mysqli_query("UPDATE fe_users SET `group` = 5 WHERE `group`='".$group."'");
if(mysqli_num_rows($user_update)==1){
return 'ok, updated user';
} else {
// database error
return 'not ok, unable to update user record';
}
}//end while row
}else{
return 'No results were found for this group.';
}
By selecting just the column you want, you reduce the query's overhead. By comparing the initial result to 0 instead of 1, you allow for groups with many members. By wrapping the update function in a while loop, you can loop through all the returned results, and update records for each one. By moving the test that returns 'ok'/'not ok' to check for success on the update operation, you're able to isolate database errors. The final else statement tells you if no update operation was performed because there are no members of the group.
BTW, for future-compatible code, I recommend using mysqli, as the "mysql_query" family of PHP functions are officially deprecated. See http://www.php.net/manual/en/mysqli.query.php for a quick start, it's largely the same thing.

How do I show a user's credit based on their session

I'm developing a simple LAMP app where users can credit their account using Paypal. I suspect this is a simple issue, but have spent quite a while experimenting to no avail and would appreciate any thoughts:
System has a user management system working fine using sessions, but I can't get it to display the current user's credit.
But I've been trying things along the lines of:
$result = mysql_query("
SELECT *
FROM users
INNER JOIN account
ON account.UserID=account.UserID
ORDER BY account.accountID");
while($_SESSION['Username'] = $row['Username'] )
{
echo $row['Username'];
echo $row['Credit'];
}
I suspect the while statement is invalid, but I want it to echo username and credit where the current session username = the username stored in the database.
Thanks so much for taking a look - very much appreciated.
Okay there is actually a lot wrong with your code that can not be fixed by you as you have obviously no knowledge of php at all.
But let me explain this so you can get a good understanding of what you did wrong:
First of all, your mysql statement is just wrong.
Why do you join a field on itself? You won't get the corresponding users <-> account rows because users is never actually joined.
In addition to that, if you want to fetch a single row (you only want one because you only want to echo the data of one user, fetching more is only heavier in resources), tell mysql to do that. A simple example would be "WHERE a="b" LIMIT 1 (select only row where a is equal to "b", return after finding the first).
Now, to read something from your query, you need to fetch the corresponding data.
You can do that by using mysql_fetch_assoc / mysql_fetch_array / mysql_fetch_object.
This would look something like this: $data = mysql_fetch_array($query);.
In this case, you don't need to use a while() loop as you only have one row. A while loop is only necessary if you want to work with more then one row.
The rest of your code would be correct, though you don't need to call echo twice. You can simply connect both variables with a ".": echo $row['Username'].$row['Credit'];.
If you want to insert a space in between, connect it with another dot: echo $row['Username']." ".$row['Credit'];.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if ($row['Username'] == $_SESSION['Username'])
{
echo $row['Username'];
echo $row['Credit'];
break; // I believe username is unuque.
}
}
But it's much better to get just 1 row from the table :
$result = mysql_query("
SELECT *
FROM users
INNER JOIN account
ON account.UserID=users.UserID
WHERE Username ='".mysql_real_escape_string($_SESSION['Username'])."'" );
if ($result && $row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo .....
}
You only have a mysql result, now you have to return that information as an associative array (or object)
while ($row = mysql_fetch_assoc($result)) {
if ($_SESSION['username'] == $row['Username']) {
echo $row['Username'];
echo $row['Credit'];
}
}
It appears as if you are using $_SESSION['username'] as a way to check user authentication on the site, much better to use a salted+hashed version of the username and possibly the login time (never include the password).
One thing that jumps out at me is that your query is joining on:
account.UserID=account.UserID
instead of:
account.UserID=user.ID
Also, this is not right:
while($_SESSION['Username'] = $row['Username'] )
The = sign is for assignment, not comparison, so you're actually setting the value of $_SESSION['Username'] to $row['Username']. Then, the expression is evaluated as a boolean (since it's within a while conditional), and if it's true once, it'll be true forever. Infinite loop city.

How to list rows for a query or display 'no records' using a single query

How to list records for a query and to display "no records" when no rows returned using a single query?
Currently I am using a COUNT(*) query or using mysql_num_rows() function; then another query in different result set to list data. Can you tell me if it is possible to accomplish the same with a single query?
Important: I assume that the OP uses PHP as (s)he mentions mysql_num_rows. And I hope (s)he will tell me if I am wrong.
It is your job in PHP to check whether the result is an empty set or not. I don't understand why you have to do another query. Maybe you have to clarify your question.
Here a more complete example:
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
// If if result set contains rows
if(0 == mysql_num_rows($result)) {
echo 'no records';
}
else { // Loop over the result set
while(row = mysql_fetch_array($result)) {
// do whatever you want with the data here
}
}
Reference: mysql_num_rows, mysql_fetch_array
Even if you don't use PHP, the approach is the same in other languages and there should be similar functions available.
why do you need another query after mysql_num_rows?
why not to just run your query and then check results with mysql_num_rows?
Try Something like following
if (mysql_num_rows == '0')
'No Records'
else
//YOUE CODE HERE

Categories