php while loop running only once - php

I have a php script for check the availability of some data. I call this script from external jquery. the jquery is running fine. here is my php:
<?php
$avares = checkAva($fi_nm, $tbl_nm, $txtval);
echo $avares;
function checkAva($field, $table, $curval) {
$avres = mysql_query("SELECT " . $field . " FROM " . $table . "") or die("query failed");
while ($a_row = mysql_fetch_array($avres)) {
$dbval = $a_row[$field];
if ($curval == $dbval) {
return "no";
} else {
return "yes";
}
}
}
?>
$curval is the variable coming from external jquery. my problem is that the while loop seems to run only once though there are lot of entries in the DB. I checked it with an integer variable and the while loop seems to run only once. can you help me to solve that?

Look at your code.
while ($a_row = mysql_fetch_array($avres)) {
$dbval = $a_row[$field];
if ($curval == $dbval) {
return "no";
} else {
return "yes";
}
}
you have used return, if its true it returns and false then also returns change those according to your needs. The return statement immediately ends execution of the current function

It will by design as you have a return statement. From what you have said your not actually wanting it to return but to set a variable that at end of execution will return no or yes. I could be wrong on this but hey ho.
<?php
echo checkAva($fi_nm, $tbl_nm, $txtval);
function checkAva($field, $table, $curval) {
$avres = mysql_query("SELECT " . $field . " FROM " . $table) or die("query failed");
$noOrYes = "yes";
while ($a_row = mysql_fetch_array($avres)) {
if($curval == $a_row[$field]) {
$noOrYes = "no";
}
}
return $noOrYes;
}
?>

The possible issue that can cause Loop to iterate once are:
Error in the Variable used for the $query and $result
Same name Variable inside and outside of the Loop
Incorrect placement of Return statement
Invalid Mysql Statement

Directly put the condition in your Query like
function checkAva($field, $table, $curval) {
$avres = mysql_query("SELECT " . $field . " FROM " . $table . "
WHERE `".$field."` = '".$curVal."'");
$res = mysql_fetch_array($avres);
if(is_array($res) && count($res) > 0)
return "Yes";
else
return "No";
}
Instead of getting all the results and checking with each one of the result you directly put a condition to extract the results which satisfies your condition.This will be suggestable if you have many records.

You need to put one of the return outside of the while loop.
For example if you just wanted to check if $curval == $dbval
while ($a_row = mysql_fetch_array($avres)) {
$dbval = $a_row[$field];
//If the condition was met return with a no
if ($curval == $dbval) {
return "no";
}
}
//If the condition was not met return yes
return yes;
That's basically what you need to do so the loop will run until your condition was met or not at all.

Related

Working with multiple rows from a MySQL query

Before I begin, I want to point out that I can solve my problem. I've rehearsed enough in PHP to be able to get a workaround to what I'm trying to do. However I want to make it modular; without going too much into detail to further confuse my problem, I will simplify what I am trying to do so that way it does not detract from the purpose of what I'm doing. Keep that in mind.
I am developing a simple CMS to manage a user database and edit their information. It features pagination (which works), and a button to the left that you click to open up a form to edit their information and submit it to the database (which also works).
What does not work is displaying each row from MySQL in a table using a very basic script which I won't get into too much detail on how it works. But it basically does a database query with this:
SELECT * FROM users OFFSET (insert offset here) LIMIT (insert limit here)
Essentially, with pagination, it tells what number to offset, and the limit is how many users to display per page. These are set, defined, and tested to be accurate and they do work. However, I am not too familiar how to handle these results.
Here is an example query on page 2 for this CMS:
SELECT * FROM users OFFSET 10 LIMIT 10
This should return 10 rows, 10 users down in the database. And it does, when I try this command in command prompt, it gives me what I need:
But when I try to handle this data in PHP like this:
<?php
while ($row = $db->query($pagination->get_content(), "row")) {
print_r($row);
}
?>
$db->query method is:
public function query($sql, $type = "assoc") {
$this->last_query = $sql;
$result = mysql_query($sql, $this->connection);
$this->confirm_query($result);
if ($type == "row") {
return mysql_fetch_row($result);
} elseif ($type == "assoc" || true) {
return mysql_fetch_assoc($result);
} elseif ($type == "array") {
return mysql_fetch_array($result);
} elseif ($type == false) {
return $result;
}
}
$pagination->get_content method is:
public function get_content() {
global $db;
$query = $this->base_sql;
if (!isset($_GET["page"])) {
$query .= " LIMIT {$this->default_limit}";
return $query;
} elseif (isset($_GET["page"]) && $_GET["page"] == 1) {
$query .= " LIMIT {$this->default_limit}";
return $query;
} elseif (isset($_GET["page"])) {
$query .= " LIMIT {$this->default_limit}";
$query .= " OFFSET " . (($_GET["page"] * $this->default_limit) - 10);
return $query;
}
}
And my results from the while loop (which should print out each row of the database, no?) gives me the same row everytime, continuously until PHP hits the memory limit/timeout limit.
Forgive me if its something simple. I rarely ever handle database data in this manner. What I want it to do is show the 10 users I requested. Feel free to ask any questions.
AFTER SOME COMMENTS, I'VE DECIDED TO SWITCH TO MYSQLI FUNCTIONS AND IT WORKS
// performs a query, does a number of actions dependant on $type
public function query($sql, $type = false) {
$sql = $this->escape($sql);
if ($result = $this->db->query($sql)) {
if ($type == false) {
return $result;
} elseif ($type == true || "assoc") {
if ($result->num_rows >= 2) {
$array;
$i = 1;
while ($row = $result->fetch_assoc()) {
$array[$i] = $row;
$i++;
}
return $array;
} elseif ($result->num_rows == 1) {
return $result->fetch_assoc();
}
} elseif ($type == "array") {
if ($result->num_rows >= 2) {
$array;
$i = 1;
while ($row = $result->fetch_array()) {
$array[$i] = $row;
$i++;
}
return $array;
} elseif ($result->num_rows == 1) {
return $result->fetch_array();
}
}
} else {
die("There was an error running the query, throwing error: " . $this->db->error);
}
}
Basically, in short, I took my entire database, deleted it, and remade another one based on the OOD mysqli (using the class mysqli) and reformatted it into a class that extends mysqli. A better look at the full script can be found here:
http://pastebin.com/Bc00hESn
And yes, it does what I want it to. It queries multiple rows, and I can handle them however I wish using the very same methods I planned to do them in. Thank you for the help.
I think you should be using mysql_fetch_assoc():
<?php
while ($row = $db->query($pagination->get_content())) {
print_r($row);
}
?>

GET Multiple MySQL Rows, Form PHP Variables, and Put Into Json Encoded Array

I am trying to GET different rows from different columns in php/mysql, and pack them into an array. I am able to successfully GET a jason encoded array back IF all values in the GET string match. However, if there is no match, the code echos 'no match', and without the array. I know this is because of the way my code is formatted. What I would like help figuring out, is how to format my code so that it just displays "null" in the array for the match it couldn't find.
Here is my code:
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode($fbaddra);
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['addr'];
} else {
$fbaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['addr'];
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
UPDATE: The GET Request
I would like the GET request below to return the full array, with whatever value that didn't match as 'null' inside the array.
domain.com/api/core/engine.php?a=fbaddra&facebook=username&facebookp=pagename
The GET above currently returns null.
Requests that work:
domain.com/api/core/engine.php?a=fbaddra&facebook=username or domain.com/api/core/engine.php?a=fbaddra&facebookp=pagename
These requests return the full array with the values that match, or null for the values that don't.
TL;DR
I need assistance figuring out how to format code to give back the full array with a value of 'null' for no match found in a row.
rather than assigning as 'null' assign null. Your full code as follows :
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode('no match');
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
You can even leave else part altogether.
Check your code in this fragment you not use same names for variables:
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = 'null';
}
$fbaddr not is same as $fpaddr, this assign wrong result to if statement.
It was the mysql query that was the problem.
For those who come across this, and need something similar, you'll need to format your query like this:
** MYSQL QUERY **
if ($_GET['PUTVALUEHERE']) {
$g = $_GET['PUTVALUEHERE'];
$gq = $mysqli->real_escape_string($g);
$q1 = "SELECT * FROM `addrbook` WHERE `facebookp` = '".$gq."' OR `facebook` = '".$gq."'";
}
** PHP CODE **
if($_GET['PUTVALUEHERE']{
echo json_encode($row['addr']);
}

How to check if php mysqli_fetch_array is empty before while loop

I wanted to make sure there are results before running the while loop but all the methods I am trying seem to remove the first result.
$nearbyResult = mysqli_query($con,$sqlNearby);
if(mysqli_fetch_array($nearbyResult) == 0) {
echo '<p>No results found, Add your property here.</p>';
} else {
while($rowNearby = mysqli_fetch_array($nearbyResult)) {
}
}
This line will take the first row of your result set and chuck it in the bin:
if(mysqli_fetch_array($nearbyResult) == 0) {
Change to:
if( ! mysqli_num_rows($nearbyResult) ) {
And check your freakin function returns:
if( ! $nearbyResult = mysqli_query($con,$sqlNearby) ) {
echo "Mysql error: " . mysqli_error($con);
}
You can use the mysql_row_count method to count how many rows are returned in your query http://php.net/manual/en/mysqli-result.num-rows.php
Try assigning the results to a variable as part of your if statement. If mysqli_fetch_array() has no result set to work with it will return false.
if($rowNearby = mysqli_fetch_array($nearbyResult)) {
//There was a result, work with it here
doStuffWith($rowNearby);
} else {
//No records in your result set, handle as desired
}

php if condition

I can't find anything wrong with this... This should work right?
function ConfirmedNumber()
{
$rs = mysql_query("CALL ConfirmedNumber('" , $_SESSION['UserID'] . "',#Active)");
while ($row = mysql_fetch_assoc($rs))
{
if ($row['Active'] = 1)
{
return true;
}
}
return false;
}
Assuming the Stored procedure returns a single row with the value '1' in it then I can call the function like this right?
if (ConfirmedNumber())
{
//do some stuff.
}
To expand on my comment:
if ($row['Active'] = 1) should be if ($row['Active'] == 1) to work correctly.
If you want to avoid accidentally doing this in future, you could write your if statements like this:
if (1 == $row['Active'])
This way, you can't accidentally use = as PHP will throw a Fatal Error. You can read more about Comparison Operators at PHP.net
Comment below with the full answer:
The call to the stored proc... line $rs = mysql_query("CALL ConfirmedNumber('" . $_SESSION['UserID'] . "',#Active)"); had a comma instead of the period in the initial post.
you forgot your operator in your IF statement. Change it to this:
if ($row['Active'] == 1)
or even shorter
if ($row['Active'])
it can be something like this
function ConfirmedNumber($id)
{
$rs = mysql_query("CALL ConfirmedNumber('" . $id . "',#Active)");
while ($row = mysql_fetch_assoc($rs))
{
if ($row['Active'] == 1)
{
return true;
}
}
return false;
}
ConfirmedNumber($_SESSION['UserID']);

Can anyone explain the following PHP Code?

Can anyone explain what the following PHP Code does
function query($query_string)
{
if ($query_string == "") {
return 0;
}
if (!$this->connect()) {
return 0;
};
if ($this->QueryID) {
$this->free_result();
}
if ($this->RecordsPerPage && $this->PageNumber) {
$query_string .= " LIMIT " . (($this->PageNumber - 1) * $this->RecordsPerPage) . ", " . $this->RecordsPerPage;
$this->RecordsPerPage = 0;
$this->PageNumber = 0;
} else if ($this->RecordsPerPage) {
$query_string .= " LIMIT " . $this->Offset . ", " . $this->RecordsPerPage;
$this->Offset = 0;
$this->RecordsPerPage = 0;
}
$this->QueryID = #mysql_query($query_string, $this->LinkID);
$this->Row = 0;
$this->Errno = mysql_errno();
$this->Error = mysql_error();
if (!$this->QueryID) {
$this->halt("Invalid SQL: " . $query_string);
}
return $this->QueryID;
}
function next_record()
{
if (!$this->QueryID) {
$this->halt("next_record called with no query pending.");
return 0;
}
$this->Record = #mysql_fetch_array($this->QueryID);
$this->Row += 1;
$this->Errno = mysql_errno();
$this->Error = mysql_error();
$stat = is_array($this->Record);
if (!$stat && $this->AutoFree) {
$this->free_result();
}
return $stat;
}
Can the above be done in a simpler way , would it be wise to use an ORM ?
The first class method looks like it performs a MySQL query and adds a LIMIT clause for pagination. The second moves the current query onto the next record, while incrementing the pagination counters.
In more detail, here's the first sample:
Exit the method if the query is empty or the database connection doesn't exist.
Free any existing query.
If the number of records per page and page number are set:
Add them to the LIMIT clause of the query.
And reset them to 0.
Otherwise if records per page is set:
Add it to the LIMIT clause of the query.
And reset them to 0.
Run the query.
Set the current row to 0.
Collect errors.
If the query failed halt with the error.
Return the query.
And the second:
If the query is not set halt with an error.
Fetch row information as an array for the current row.
Increment the row number.
Catch any errors.
If the result isn't an array free/close the query.
Otherwise return the result set.
Yes you are right Ross it something like pagination function in a class which calls the records one by one.

Categories