PHP How to compare each array value with my specified value? - php

Say for example this is my code:
$query = "SELECT * FROM ...";
$exec_query = mysql_query($query, $db_connect);
$fetchdetails = mysql_fetch_array($exec_query);
I am using an if condition like this:
if ($fetchdetails['field_name'] == 3) {
do something;
}
else {
}
But in this, only 1 row is compared from the fetchdetails array. What can I do to compare each row in that array with 3? I don't want any OOP's solutions, please, I want to stick with traditional coding. Thank you.

You should try this:
while($fetchdetails = mysql_fetch_array($exec_query)) {
if ($fetchdetails['field_name'] == 3) {
do something;
}
else {
}
}
That's because, with the while(...) condition, you'll iterate over all db (selected) records.
The loop will stop in an automatic way as soon as mysql_fetch_array finish record.
I'll remember you that mysql_fetch_array
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. (from manual)
and that will allow "you" to stop iteration process.

If you mean that you want to compare every row of the $fetchdetails array, then
foreach($fetchdetails as $index => $value) {
if($value == 3) {
// do something
}
}
Should do it! If you want to iterate over every SQL value, see the other answer.

Related

pdo how to check if it is 1st record that retrieve from database?

$sql3 = "SELECT member FROM levels where upline = ? AND level=1";
$q3 = $conn->prepare($sql3);
$q3->execute(array("$level2downlines"));
while($r3 = $q3->fetch(PDO::FETCH_ASSOC)){
$level3downlines = $r3['member'];
if (it is 1st record){
echo "make orange juice";
}else{
echo "make all juice";
}
}
Let say output are 3 records from database "Zac", "Michelle", Andrew". "Zac" is the 1st record get from database, how to write the "if" statement to check if the records is 1st record or not?
First off, if the order of records returned matters, you must explicitly include an ORDER BY clause in your query to specify which column to sort results on. Otherwise, the order of rows returned is technically indeterminate.
To operate differently on the first fetched row than on later rows, you may simply call fetch() outside the loop first, then loop over the remainder. Each call to PDOStatement::fetch() will advance the rowset record pointer, so the while loop will only iterate the records after the one already retrieved.
// Fetch the first row from the rowset
$r3 = $q3->fetch(PDO::FETCH_ASSOC);
$level3downlines = $r3['member'];
// Do actions specific to 1st row before the loop
echo "make orange juice";
// Then fetch the remaining rows with a loop
// and perform the their actions in the loop.
// The rowset record pointer has advanced beyond the 1st row
while($r3 = $q3->fetch(PDO::FETCH_ASSOC)){
$level3downlines = $r3['member'];
echo "make all juice";
}
In practice, I don't often do operations while fetching rows unless the rowset is very large. Instead I would more likely retrieve all rows as an array where I can more easily perform array operations on the set.
// Get all rows
$all_rows = $q3->fetchAll(PDO::FETCH_ASSOC);
// Pull the first row off the set
$first_row = array_shift($all_rows);
// do whatever with $first_row
// Loop over the other rows
foreach ($all_rows as $index => $row) {
// Do whatever with $row
}
Instead of using array_shift() in that way, when using $index => $row in the foreach loop, you could also check $index == 0 to operate on your first row. You may find this more understandable.
foreach ($q3->fetchAll(PDO::FETCH_ASSOC) as $index => $row) {
// First row
if ($index == 0) {
// Do first row actions
}
else {
// Do common actions for remaining rows.
}
}
I'm not sure if I understood you correctly, but you want to do a special action for the first row,
$sql3 = "SELECT member FROM levels where upline = ? AND level=1";
$q3 = $conn->prepare($sql3);
$q3->execute(array("$level2downlines"));
$first_row = true;
while($r3 = $q3->fetch(PDO::FETCH_ASSOC)){
$level3downlines = $r3['member'];
if ($first_row){
echo "make orange juice";
$first_row = false;
}else{
echo "make all juice";
}
}
UPDATE: Michael Berkowski's answer is better and faster.

PHP for each result excluding values from array

I queried a table into an array but I would like to exclude certain values from one of the columns as to spits out each row. For example.
foreach($results as $row)
{
if($row['sku'] != "sku-1"){
echo $row['sku']." ";
}
}
So lets say the table has 4 rows with a value of sku-1, sku-2, sku-3 and sku-4. The above Foreach code would echo out "sku-2 sku-3 sku-4". Is there a way I can make an array of what values I would want to exclude? Like I'd have an array called $skuarray = "sku-2, sku-4" and instead of
if($row['sku'] != "sku-2" || $row['sku'] != "sku-4"){
have that $skuarray in there where it'll echo "sku-1, sku-3"? Thanks!
EDIT
I could somehow exclude it when I query it. I'm querying it from table SKUTABLE and the column is SKU. The problem is I need to exclude unique values from column SKU so I thought if there was an easy way to just throw in all the ones I want to exclude into an array that'd be great.
You could use the array_diff(array1, array2, [...arrayN]) function, which takes at least two arrays, and returns an array of only those values of array1 which are not in any of the subsequent arrays. Example:
$input = array(0=>'sku-1',1=>'sku-2',2=>'sku-3',3=>'sku-4');
$exclude = array('sku-1','sku-3','sku-4');
$result = array_diff($input, $exclude);
print_r($result);
Will print
array(1=>'sku-2');
Use in_array:
$skuarray = array("sku-2", "sku-4");
foreach($results as $row)
{
if(!in_array($row['sku'], $skuarray)){
echo $row['sku']." ";
}
}
You can use array_filter in combination with in_array.
$filtered_results = array_filter($results, function ($row) {
return in_array($row["sku"], $skuarray) === false;
});

check while loop out put any data from query

$query=$db->prepare("SELECT *...
while($data=$query->fetch(PDO::FETCH_ASSOC)){...}
I have a query use while loop print out the data.
How can I check if while loop didn't fetch out any data(0 row from db), so I can print "0 result" on screen.
I don't want to make extra query for COUNT(*), is any way do check from while loop?
You have to use $sth = $query->execute() (and $sth->fetch() instead of $query->fetch() ) first, then $sth->rowCount will give you the number of results.
Just put a flag inside the loop to ensure you entered at least once.
Something like:
$flag = false;
$query=$db->prepare("SELECT *...");
while($data=$query->fetch(PDO::FETCH_ASSOC)){
$flag = true;
}
if ($flag) {} //entered
Added semicolon, thanks #Fred -ii
So you want to count the amount of results you get. In that case, you can just count a var up inside the loop:
while($data=$query->fetch(PDO::FETCH_ASSOC)){
$i++;
//your code here
}
If you want to check if you got no data, you can check $data:
while($data=$query->fetch(PDO::FETCH_ASSOC)){
if($data === false) {
echo "0 result";
}
}

How can this loop loop 4 times only?

I'm making a PHP to check for the friends ID in a friends relation table, then returns the info of the friends.
The problem is, the first loop loops 2 times, and that's right, when I check for the value of the count of the second loop, I find it equals to 4, how can this happen and the second table got 4 rows?
Here's the code:
while ($rowres = mysql_fetch_array($listres))
{
if ($_GET["ID"] == $rowres["ID"])
{
while ($row = mysql_fetch_array($result))
{
$count++;
if ($rowres["FID"] == $row["ID"])
{
}
}
}
}
the inner loop will loop through result only one loop, because after it loops to the last element of $result pointer of result will be point after last element, the easiest way here will be probably reset pointer to the top:
while ($rowres = mysql_fetch_array($listres))
{
if ($_GET["ID"] == $rowres["ID"])
{
mysql_data_seek($result,0); //<-HERE
while ($row = mysql_fetch_array($result))
{
$count++;
if ($rowres["FID"] == $row["ID"])
{
}
}
}
}
please note: mysql extension is DEPRECATED and will be removed in the future. Instead use mysqli or PDO

How to Retrieve 1 Result from Custom MySQL fetch Function

Yesterday another user helped out with building a generic function for handling MySQL Queries. It looks like this:
function fetchAll($query) {
$res = mysql_query($query) or trigger_error("db: ".mysql_error()." in ".$query);
$a = array();
if ($res) {
while($row = mysql_fetch_assoc($res)) {
$a[]=$row;
}
}
return $a;
}
And to output the returned results I simply do the following:
$data = fetchAll("SELECT * FROM news_table ORDER BY id LIMIT 10");
foreach ($data as $row) {
echo $row['title'];
}
My question relates to outputting the result when there's only one result in the array. Like when displaying the current blog post of a page. I want to know if I can do it without first calling the foreach loop? Is there a way to output just the first result from the array as I do not need to loop through it.
Perhaps I could have an alternate function, as opposed to the fetchAll() one above? One that just outputs one row?
Cheers,
Scott
Yes. For example:
echo $data[0]['title'];
Basically your $data is a two-dimensional array, with the first dimension being the row number (count starts with 0), so you can access any of the rows directly if you know its number. If you only have one row, it's necessarily 0.
Just count the array
if(count($data) == 1) {
// Only one dataset
} else if(count($data) > 0) {
// foreach
} else {
// no content
}
echo $data[0]['title'];
Should print exactly what your looking for. In 2D arrays the first dimension is the array index and as array index start at 0, the above code will echo the first row in that array.

Categories