mysqli_fetch_array and if-else condition for validation - php

Something is wrong with my php,
I'm doing an account validation where if the data exist it will display "There is data" and else "No data"...
When I enter the first 'row' reference_id and submit, it shows "There is data" which is correct but when I entered the second to the last 'row' reference_id it shows "No data" even though it exist in my Database!
Database:
reference_id (varchar 250)
status (varchar250)
PHP
if (isset($_POST['submit_valid'])) {
if (!empty($_POST['reference_id']))
{
$query = mysqli_query($con, "SELECT * FROM client_record");
$result = mysqli_fetch_array($query);
if ($result['reference_id'] == $_POST['reference_id'])
{
echo"<script type='text/javascript'> alert('There is data'); window.location.href='next_page.php'; </script>";
}
if ($result['reference_id'] !== $_POST['reference_id']) {
echo"<script type='text/javascript'> alert('No data.'); window.location.href='this_page.php'; </script>";
}
}
}
I am not sure if it's the mysqli_fetch_array fault or the if-else condition is wrong?
if you guys know the problem please help me?

Your query execution currently only looks at the first row. A fetch needs to be looped to iterate over all rows. e.g.
$query = mysqli_query($con, "SELECT * FROM client_record");
$result = mysqli_fetch_array($query);
should be
$query = mysqli_query($con, "SELECT * FROM client_record");
while($result = mysqli_fetch_array($query)) {
but this is inefficient. When looking for a specific record use a where clause. Parameterized queries also will prevent SQL injections, and quoting issues. The i in the bind_param is for an integer, if your id is a string use s.
$prepared = mysqli_prepare($con, "SELECT * FROM client_record where reference_id = ?");
mysqli_stmt_bind_param($prepared, 'i', $_POST['reference_id']);
mysqli_stmt_execute($prepared);
mysqli_stmt_store_result($prepared);
while (mysqli_stmt_fetch($prepared)) {

$query = mysqli_query($con, "SELECT * FROM client_record");
$result = mysqli_fetch_array($query);
This will give you the first row from the table.
Add a WHERE reference_id = :refid clause?!
Then bind the refid parameter, so as to avoid SQL injection.

Lapiz, the problem is actually with the comparison operator:
($result['reference_id'] == $_POST['reference_id'])
This will check the first reference_id from the returned set in array.
The best way to tackle this would be to use if (in_array(5, $result)) where 5 is the needle and $result is the array haystack.
Because all you are doing is to check if the reference exists in the returned data set .
This is also good design practices, to collect results and avoid multiple reference queries each time, hit the database once and query the result set.
If its a multidemnsional array loop through the set:
foreach($result as $resultItem)
{
if(in_array("reference_id", $resultItem, true))
{
echo "There is Data";
}
}
Good Luck .

Related

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
}

Simple mysql Query to check if row exist

I want to show user if he liked a image or not..
for that I am creating php code
$userid=$_COOKIE['userid'];
$sql = "SELECT * FROM likes WHERE `user_id`='{$userid}'";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($query);
if($row){
echo "unlike";
}
else{
echo "like";
}
I can not do this for everything like 'tags', 'shares', 'comments', 'favourites' ...many
Isn't there anything simpler than this...?
Like say $row_check=mysqli_check_exist($table,$column_name,$userid);
use mysql fetch row method
$num_row = mysqli_num_rows($query);
if($num_row>0)
{
//add your code
}
else
{
//add your code
}
There are a lot of ways of doing this really but if you arnt going to use any more information then weither or not the user has liked it doing select * is a bad idea. The reason why is that you are asking the database to return the value of every column in that table.
Assuming its a small database its probably not a problem no but as your database gets bigger you are puting more load on it then you need you should try and only select the columns you need and intend to use. Ok in this case the userid is probably indexed and its only one row, but if you get in the habit of doing it here you may do it else where as well.
try this instead.
$userid=$_COOKIE['userid'];
$sql = "SELECT count(user_id) as total FROM likes WHERE `user_id`='{$userid}'";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($query);
if( $row ['total'] > 0){
echo "unlike";
}
else{
echo "like";
}
This way we are just getting the total. simple and elegant
Use mysqli_num_rows($query) if > 0 exist
You simply need to count the available records using
mysqli_num_rows($query);
This will return a number (count) of available records
So simple put a check like this :
$userid=$_COOKIE['userid'];
$sql = "SELECT * FROM likes WHERE `user_id`='{$userid}'";
$query = mysqli_query($conn, $sql);
$count = mysqli_num_rows($query);
if($count>0){
echo "unlike";
}
else{
echo "like";
}

Multiple SELECT Statements and INSERTS in 1 file

I'm working with a file and I'm attempting to do multiple select statements one after another and insert some values. So far the insert and the select I've got working together but when attempting to get the last SELECT to work I get no value. Checking the SQL query in workbench and everything works fine. Here's the code:
$id = "SELECT idaccount FROM `animator`.`account` WHERE email = '$Email'";
$result = mysqli_query($dbc, $id) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($result))
{
echo $row[0];
$insert_into_user = "INSERT INTO `animator`.`user` (idaccount) VALUES ('$row[0]')";
}
$select_userid = "SELECT iduser FROM `animator`.`user` WHERE iduser = '$row[0]'";
$results = mysqli_query($dbc, $select_userid) or die("Error: ".mysqli_error($dbc));
while($rows = mysqli_fetch_array($results))
{
echo $rows[0];
}
I do not want to use $mysqli->multi_query because of previous problems I ran into. Any suggestions? And yes I know the naming conventions are close naming... They will be changed shortly.
Your code makes no sense. You repeatedly build/re-build the $insert_int-User query, and then NEVER actually execute the query. The $select_userid query will use only the LAST retrieved $row[0] value from the first query. Since that last "row" will be a boolean FALSE to signify that no more data is available $row[0] will actually be trying to de-reference that boolean FALSE as an array.
Since you're effectively only doing 2 select queries (or at least trying to), why not re-write as a single two-value joined query?
SELECT iduser, idaccount
FROM account
LEFT JOIN user ON user.iduser=account.idaccount
WHERE email='$Email';
I'm not sure what you're trying to do in your code exactly but that a look at this...
// create select statement to get all accounts where email=$Email from animator.account
$id_query = "SELECT idaccount FROM animator.account WHERE email = '$Email'";
echo $id_query."\n";
// run select statement for email=$mail
$select_results = mysqli_query($dbc, $id_query) or die("Error: ".mysqli_error($dbc));
// if we got some rows back from the database...
if ($select_results!==false)
{
$row_count = 0;
// loop through all results
while($row = mysqli_fetch_array($result))
{
$idaccount = $row[0];
echo "\n\n-- Row #$row_count --------------------------------------------\n";
echo $idaccount."\n";
// create insert statement for this idaccount
$insert_into_user = "INSERT INTO animator.user (idaccount) VALUES ('$idaccount')";
echo $insert_into_user."\n";
// run insert statement for this idaccount
$insert_results = mysqli_query($dbc, $insert_into_user) or die("Error: ".mysqli_error($dbc));
// if our insert statement worked...
if ($insert_results!==false)
{
// Returns the auto generated id used in the last query
$last_inisert_id = mysqli_insert_id($dbc);
echo $last_inisert_id."\n";
}
else
{
echo "insert statement did not work.\n";
}
$row_count++;
}
}
// we didn't get any rows back from the DB for email=$Email
else
{
echo "select query returned no results...? \n";
}

check if record exist in mysql db

I think this should work but it is not...
Basically i am trying to check mysql db to see if there is a record that meets the 2 variables..if no do one thing if yes do another thing. the result is always no at this point.
$result = mysql_query("SELECT 'lastname' FROM 'Cust_Releases' WHERE 'lastname' = '$usercheck' AND 'TripID'= '$RLtripid'");
echo $result;
if(mysql_num_rows($result) == 0) {
echo"no";// row not found, do stuff...
}
else {
echo"yes"; // do other stuff...
}
First of all, stop using mysql_* functions because this extension is deprecated as of PHP 5.5.0.
Second always use the (`) symbol around database names, table names and column names.
You have a reserved word used RELEASE.
$sql = "SELECT `lastname` FROM `Releases` WHERE `lastname` = '$usercheck' AND `TripID` = '$RLtripid'";
Reserved words you find here
$result = mysql_query("SELECT lastname FROM `Releases` WHERE lastname = '$usercheck' AND TripID= '$RLtripid' LIMIT 1");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
echo $result;
if(mysql_num_rows($result) == 0) {
echo"no";// row not found, do stuff...
}
else {
echo"yes"; // do other stuff...
}
Escaping 'Releases', as Bondye suggested
Adding 'LIMIT 1' to your query to allow the possibility of an early-out when there is more than one matching record. You don't appear to need the total count. May not make any difference if unique constraints exist which guarantee that only one row can be returned
mysql_query is deprecated. In real code you should be using PDO and prepared statements / bind variables!
debugging is a very important thing in programming. first do make sure that the varibales $usercheck, and $RLtripid contain values.
-----------------------
$sql = "SELECT `lastname` FROM `Cust_Releases` WHERE `lastname` = '$usercheck' AND `TripID`= '$RLtripid'";
echo $sql;
$result = mysql_query($sql);
....-------------------
Try this code. It will help you
$result = mysql_query("SELECT COUNT( * ) from Cust_Releases lastname = '$usercheck' AND TripID= '$RLtripid'");
if($result == 0) {
echo"no";// row not found, do stuff...
}
else {
echo"yes"; // do other stuff...
}

how can i check if a variable is saved or not in the db?

I have this code:
$local_id = $_GET['id'];
$sql = dbquery("SELECT * FROM `videos` WHERE `id` = ".$local_id." LIMIT 0, 1");
while($row = mysql_fetch_array($sql)){
$video_id = $row["youtube_id"];
// the rest
}
how can i check if $local_id does not exist in the db and display an error?
mysql_num_rows
if(mysql_num_rows($sql) == 0) {
//Show error
}
$sql = dbquery("select count(*) from videos where id = ".$local_id." LIMIT 0, 1");
$row = mysql_fetch_row($sql);
if($row[0] == 0)
echo 'error';
You can use the following query:
"SELECT COUNT(*) FROM `videos` WHERE `id` = ".mysql_real_escape_string($local_id)
This query will return one number: how many records have matched your query. If this is zero, you surely know that there are no records with this ID.
This is more optimal than other solutions posted in case you only want to check for the existence of the ID, and don't need the data (if you use SELECT * ..., all the data will be unnecessarily sent from MySQL to you). Otherwise mysql_num_rows() is the best choice, as #Ryan Doherty correctly posted.
Be sure to ALWAYS escape data that came from the outside (this time GET) before you put it into a query (mysql_real_escape_string() for MySQL).
If you fail to do so, you are a possible victim for SQL Injection.
You could have a $count variable and increment it in the while loop. After the loop, check the count, if it is 0, then echo an error message.

Categories