PHP - Check table to see if entry exists - php

I need to check if a record exists in a table before adding it.
I've done some digging and this is what people keep coming back too:
$result= mysql_query("SELECT id FROM mytable WHERE city = 'c7'");
if(mysql_num_rows($result) == 0) {
// row not found, do stuff...
} else {
//row found, do other stuff...
}
or some variation there of.
This logic is exactly what I need except for the fact that $result is never returning a positive result.
The record does exist and should return a positive result.
I also tried
$sql="SELECT COUNT(email) FROM table WHERE email=$mail;";
$yesorno = mysqli_query($sql);
echo $yesorno ;
as a test and the echo returns no value.

you need to check first if the query succeed running maybe there is a problem with it
$Query = "Select id from mytable where city = 'c7' ";
if($result = mysql_query($Query)) {
if ( mysql_num_rows($result) == 0 ) {
// no rows found ;
} else {
// row exist ;
}
} else {
echo "Query failed ". $Query;
}

Related

Create a "Secret Santa" generator using MySQL and PHP

I am trying to create a Secret Santa system using a PHP page and a MySQL database to store the details so if someone forgets their match they can re-request it.
Step 1: I created a random number generator based on the number of people in the list in the database.
Count Function:
$maxSQL = "SELECT COUNT(id) as total FROM secretsanta";
$maxRS = mysqli_query($conn, $maxSQL);
$maxQuery = mysqli_fetch_array($maxRS);
$maxpersons = $maxQuery['total'];
Then the Random Number Generator:
$assigned = rand(1,$maxpersons);
Step 2: Test if the random number matches the persons own id and regenerate a new number if true.
do {
$assigned = rand(1,$maxpersons);
} while ($assigned==$id);
Step 3: Write the paired id to the persons database record.
$assignSQL = "UPDATE secretsanta SET assigned = '".$assigned."' WHERE secretsanta.id = ".$id;
if (mysqli_query($conn, $assignSQL)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
The Problem: Now I need to check that other people aren't assigned to that person or otherwise some could miss out and others would get more than others.
I tried to implement a function that contained a query to test each record to see if that number already existed and was hoping to add it as a condition to perhaps a while or do while statement?
if (!function_exists('checkRandom')){
function checkRandom($funcid){
$Check_SQL = "SELECT assigned FROM secretsanta ORDER BY id ASC";
$Check_RES = mysqli_query($conn, $Check_SQL);
if (Check_RES) {
while ($CheckArray = mysqli_fetch_array($Check_RES, MYSQLI_ASSOC)) {
$CheckAsgn = $CheckArray['assigned'];
if ($funcid==$CheckAsgn) {return true;}else{return false;}
}
}
}
}
Then implement it into the do while statement like this:
do {
$assigned = rand(1,$maxpersons);
} while ($assigned==$id||checkRandom($assigned));
No luck so far...HELP!.. please :)
P.S. I know there are websites that already do this, I just don't trust them to give out mine and family email address' if I can make my own private version myself.
Using your method, the first few assignments will be done with no problem, but imagine the last unassigned entry and how many times it will try a random number only to find the person with that id is already assigned..
I'm gonna give you another approach to your problem: for each user that you want to assign a santa to, make a new SELECT statement with a WHERE clause that lets you select only those users that are not assigned yet.
check out my code and see if that helps you. I just typed this and didnt test it so there could be some mistakes.
// load all unassigned users into an array
$unassignedUsers = [];
$query = "SELECT id, assigned FROM secretsanta WHERE assigned is NULL";
$res = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($res){
$unassignedUsers[] = $row;
}
if(count($unassignedUsers) == 1){
echo 'There is only 1 unassigned user. Therefore he cannot be matched';
} else {
// for loop for each user in DB that is not assigned yet
//for ($i = 1;$i <= count($unassignedUsers); $i++){
$i = 0;
foreach($unassignedUsers as $user)
// if its the second-to-last iterations of the for-loop, check for legality of the last one
if(count($unassignedUsers) - $i == 1){
$lastUserID = $unassignedUsers[count($unassignedUsers)-1]['id'];
$query = "SELECT id FROM secretsanta WHERE assigned is NULL AND id = ".$lastUserID;
$res = mysqli_query($conn, $query);
$rowcount = mysqli_num_rows($res);
if ($rowcount){
// last user is still unassigned
$query = "UPDATE secretsanta SET assigned = '".$lastUserID."' WHERE id = ".$user['id'];
if(mysqli_query($conn, $query)){
echo "Record with id ".$user['id']." updated successfully";
} else {
echo "Error updating record: ".mysqli_error($conn);
}
}
} else {
// select all unassigned users
$unassignedIDs = [];
$query = "SELECT id FROM secretsanta WHERE assigned is NULL AND id <> ".$user['id'];
$res = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($res){
$unassignedIDs[] = $row['id'];
}
// get a random id from $unassignedIDs
$randomIndex = rand(0, count($unassignedIDs)-1);
$randomID = $unassignedIDs[$randomIndex];
// assign $randomID to user
$query = "UPDATE secretsanta SET assigned = '".$randomID."' WHERE id = ".$user['id'];
if(mysqli_query($conn, $query)){
echo "Record with id ".$user['id']." updated successfully";
} else {
echo "Error updating record: ".mysqli_error($conn);
}
}
$i++;
}
}
last edit: refactored whole code so it is able to be run multiple times and only assigns new users who are not assigned yet.
Step 1 is dependent on have a contiguous set of ids for the people. Think what happens if '3' leaves the company and it hires 6 to replace them....1,2,4,5,6 ($maxpersons=5)
"Now I need to check" - no you are still trying to solve the problem by guessing then seeing if your guess worked. Use an algorithm which is always going to return a correct result. The method below requires the addition of a temporary field 'sequence' of type float.
mysqli_query($conn,"UPDATE secretsanta SET sequence=RAND()");
$first=false;
$prev=false;
$all=mysqli_query($conn, "SELECT * FROM secretsanta ORDER BY sequence, id");
while ($r=mysqli_fetch_assoc($all)) {
if (false===$first) {
$first=$r['id'];
} else {
save_pair($prev, $r['id']);
}
$prev=$r['id'];
}
save_pair($prev, $first);
(but with better error checking)

PHP check if record exist in SQL [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 6 years ago.
I am trying to check if record exist in SQL and get a return -> True or False.
It returns a notice:
Notice: Trying to get property of non-object in.... if($result->num_rows > 0)
$connection = new mysqli('localhost', 'user', 'pass','db_name');
$query = "SELECT * FROM order WHERE telephone = '".$telephone."' AND order_status_id='0' ";
$result = $connection->query($query);
if($result->num_rows > 0) {
echo 'found'; // The record(s) do exist
}
else{
echo 'not found'; // No record found
}
$connection->close();
ORDER is a mysql reserved word. Using it as field name, table name or whatever except ORDER BY fieldname requires using backticks:
SELECT * FROM `order` WHERE ....
Otherwise, you will get a query error, which will turn $result into boolean false.
Also, your code is vulnerable to sql-injection.
I advise you to use prepared statements.
You are checking the rows of the query object. The query object does not contain the rows.
What you want to do is something like
$data = $result->fetch_array();
if ($data->num_rows > 0)
{
//Rows exist
} else {
//No rows exist
}
It happens in case query do not injects object in your $result variable. You can make the following changes to proceed.
if(is_object($result) && $result->num_rows > 0) {
echo 'found'; // The record(s) do exist
} else{
echo 'not found'; // No record found
}
OR
if(!empty($result->num_rows)) {
echo 'found'; // The record(s) do exist
} else{
echo 'not found'; // No record found
}
Also keep the thing simple:
$query = "SELECT * FROM `order` WHERE telephone = '$telephone' AND order_status_id='0' ";
Use like this
$sqlReq = " SELECT * FROM order WHERE telephone = '".$telephone."' AND order_status_id='0' ";
$queryReq = mysql_query($sqlReq) or die(mysql_error());
if(mysql_num_rows($queryReq) > 0)
{
echo "found";
}else{
echo "not found";
}

undefined index error in mysql xampp

$result1 = mysql_query("SELECT id FROM p_u_r WHERE p_name = '$d'");
$S=$row['id'];
if(mysql_num_rows($result1) == 0) {
row not found, do stuff...
}
this code send an error of undefined index error. I have created p_u_r table in my database but no data is inserted.
$result1 = mysql_query("SELECT id FROM p_u_r WHERE p_name = '$d'");
$S=$row['id'];
if(mysql_num_rows($result1) == 0) {
row not found, do stuff...
}
It is likely because $row... doesn't exist. You should write something like that:
// assuming you have created $d already...
$result1 = mysql_query("SELECT id FROM p_u_r WHERE p_name = '$d'");
if(mysql_num_rows($result1) == 0) {
// row not found, do stuff...
}
else {
//fetch your results using mysql_fetch_assoc() or mysql_fetch_row()
//...
}
BTW Do you know using MySQL extension is DEPRECATED and you should create code using MySQLi ?

How to handle ADOdb Execute return value

I've found several tutorials which have similar code like the following:
$sql = "select * from users";
$result = $conn1->Execute($sql);
if ($result==false) {
print 'error' . $conn1->ErrorMsg() . '<br>';
} else {
print_r($result->GetRows());
}
But how can $result ever be false? If I add a where clause which can not be fulfilled the else-branch is still taken since $result contains the column titles. Examples:
"select * from users"; // Select the whole table data
echo "$result";
leads to
id,username,password 1,peter,geheim 2,sabine,secret 3,thorsten,qwertz
Whereas
"select * from users where username = 'does not exist'";
echo "$result";
leads to
id,username,password
Therefore result is never false. What is my mistake here?
The Execute method returns false if the query itself fails, and not if it has 0 results.
If you want to check if the query returned any results you can use the RecordCount method.
$rows = $conn1->Execute($sql);
if ($rows->RecordCount() > 0) {
// Do something with your rows
} else {
// Nothing returned
}

PHP mysql COUNT not returning instead of 0

I am trying to check if a name exists. Query should return 0 because the field is empty but returning 1 instead. help.
function profile_exists($user) { //checks that profile exists
$profile_ex = mysql_query(
"SELECT COUNT(profile_name) FROM user_info WHERE id = '{$user}'");
if(!confirm_query($profile_ex)) {
return false;
} else {
if (mysql_result($profile_ex, 0) == 1) {
echo mysql_result($profile_ex, 0);
exit;
return true;
} else {
return false;
}
}
}
You have one row instead of 0 rows because COUNT(*) returns one row of data, the count which has the value of 0 in this case.
You will need to run the query and then check the value of count.
Example:
$result = mysql_query("SELECT COUNT(*) AS count FROM ...");
$row = mysql_fetch_assoc($result);
if( $row['count'] == 0){
return False;
}else{
return True;
}
Your syntax looks abit complex, try this instead:
$profile_ex = mysql_query("SELECT * FROM user_info WHERE id = '$user'");
$profile_ex = mysql_num_rows($profile_ex);
if ( $profile_ex > 0 ) {
echo "exists"; } else {
echo "doesn't exist";
}
Hope this helps
You should be using mysqli_ or PDO with prepared statements to prevent against SQL injection.
It will always return 1 because you are using an aggregate function (COUNT). Select a column from your table instead:
SELECT profile_name FROM ...
However, if you are only interested in checking whether the profile exists, use mysqli_num_rows. If you wish to check whether the profile exists and return data, use mysqli_fetch_assoc.

Categories