PHP Array comparison and filtering - php

I'm newer to PHP and sorting out some code. This is taking two phone number lists… then pulling the numbers in the 2nd list OUT of the first list, making a new filtered list. The full code worked fine when just pulling in one list. Now that I've modified it to filter the list based a 2nd list, the code now fails and I'm getting this warning:
Warning: Illegal string offset 'phone_number' in /var/www/html/send.php on line 7
// Get all of the phone numbers from the List
$sql = "SELECT phone_number FROM dial_list WHERE list_id='$list'";
$result = mysqli_query($link, $sql);
echo mysqli_error($link);
foreach ($result as $row)
{
$all_people[] = $row['phone_number'];
}
// Get phone numbers from our DNC list
$sql = "SELECT phone_number FROM dial_dnc";
$result = mysqli_query($link, $sql);
echo mysqli_error($link);
foreach ($result as $row)
{
$dnc_people[] = $row['phone_number'];
}
// Remove DNC numbers from list
$filtered_people = array_diff($all_people, $dnc_people);
foreach ($filtered_people as $row)
{
$people[] = $row['phone_number'];
}
Line 79 (where the warning comes from) is:
$people[] = $row['phone_number'];
Any help to pinpoint the error or an improvement on how to accomplish this filtering would be greatly appreciated!

You forgot to fetch results from your resultset
foreach ($result as $row) {
should be
while ($row = mysqli_fetch_assoc($result)) {

This can be easily done with mysql alone.
SELECT
dl.phone_number
FROM dial_list AS dl
INNER JOIN dial_dnc as dnc
ON (dl.phone_number = dnc.phone_number)
WHERE list_id='$list'

your $result is a traversable object, not an array. as seen in the docs
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
You can loop over the results in 2 different ways:
// precedural style
while ($row = mysqli_fetch_assoc($result)) { ... }
// OOP style
while($row = $result->fetch_assoc()) { ... }

Since you assign $all_people and $dnc_people with $row['phone_number'], $filtered_people doesn't have a phone_number key, instead being number-keyed, probably. Try
foreach($filtered_people as $key => $value)
{
$people[] = $value;
}

Related

Fetch multiple resultset from SQL Server in Laravel 5.3

Here is the code
$exec = "EXEC RPT_TEST_2resultSet";
$resultSet = \DB::select($exec);
SP is returning 3 result sets. But in php it prints first set of result set only. How to fetch the other 2 set of result sets? Tried the solution suggested by others. Was getting some other errors.
Make a foreach
check example:
foreach ($resultSet as $result) {
echo $result['someDataFromResult'];
}
This will repeat for the amount of data is in the $resultSet array
Found the simple solution for this problem.
$pdo = \DB::connection()->getPdo();
$sql = 'EXEC Test_SP_MultiResultSet';
$stmt = $pdo->query($sql);
do {
$rows = $stmt->fetchAll(\PDO::FETCH_NUM); // Keys will be start from zero , one, two
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); // Column names will be assigned for each value
if ($rows) {
$sheetData[] = $rows;
}
} while ($stmt->nextRowset());
Source Link

How can I get this php to return the entire column of an sql db

I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}

php mysql_fetch_array() not working as expected

$result = mysql_query($strSql);
foreach($bestmatch_array as $restaurant)
{
while($row = mysql_fetch_array($result))
{
if($restaurant == $row[0])
{
$value = $row[1];
}
}
}
What I am trying to do is sort the result of array formed by query according to the values stored in $bestmatch array.
I don't know what I am doing wrong but the 4th line just seems to run once. Please help guys. Thanx in advance.
php mysql_fetch_array() not working as expected
Your expectation is not right.
foreach($bestmatch_array as $restaurant)
{
// This loop will only run for first iteration of your foreach.
while($row = mysql_fetch_array($result))
{
}
// everything has been fetched by now.
}
That is a logically incorrect sequence.
You expect your inner loop to be called over and over again as many times as you have the outer loop run but record fetch does not work like that. For outer loop's first run all the rows in $result will be fetched and since you do not reset the counter after your while loop that means after the first run there will be no more rows for the next run.
Solution? Fetch the row from mysql first then use a simple in_array call to check whether that restaurant is there in your array.
$result = mysql_query($strSql);
while($row = mysql_fetch_array($result))
{
$name=$row[0];
if(in_array($name,$bestmatch_array))
$value=$name;
}
Store the results of the query in the array first:
$result = mysql_query($strSql);
$results_row = array();
while($row = mysql_fetch_array($result))
{
$results_row[] = array($row[0],$row[1]);
}
foreach($bestmatch_array as $restaurant)
{
foreach ($results_row as $key => $value)
{
if($restaurant == $results_row[$key][0])
{
$value = $results_row[$key][1];
}
}
}

Output multiple results with mysqli_fetch_assoc

What's the best way to output all results from a SELECT query?
if ($result = mysqli_query($con, "SELECT name,pic_url FROM accounts")) {
$data = mysqli_fetch_assoc($result);
var_dump($data);
mysqli_free_result($result);
}
At present dumping of $data only outputs one result, even though a quick check of mysqli_num_rows() shows two results (and there are two rows in the table).
What's the best way to output this data?
I'm essentially looking to output the name field and the pic_url for each row so I was hoping to receive my results as an array which I can then loop through using foreach
you need to use a loop.
while ($data = mysqli_fetch_assoc($result)) {
var_dump($data);
}
Use simple while loop and store in an array:
if ($result = mysqli_query($con, "SELECT name,pic_url FROM accounts"))
{
while ($data[] = mysqli_fetch_assoc($result));
}

Results of mysqli_query() returning null for last index

I am querying like this, in snippet below 1st loop takes column names and second loops push values in another array(i know this may not be an optimal way but this is what came in my mind and is solving my task). The problem is
$results = '';
$dataArray = array();
$columns_array = array();
$dataArray = array();
$results = mysqli_query($mysqli, ("SELECT
DISTINCT states_drg.`Provider State`,
SUM(states_drg.`Total Discharges`) AS discharges
FROM states_drg
GROUP BY states_drg.`Provider State`")
);
$columns_names = mysqli_fetch_assoc($results);
foreach ($columns_names as $key => $value) {
array_push($columns_array, $key);
}
array_push($dataArray, $columns_array);
foreach ($results as $result) {
array_push($dataArray, mysqli_fetch_row($results));
}
print_r($dataArray);
echo json_encode($dataArray, JSON_NUMERIC_CHECK);
exit;
);
Query runs absolutely fine in query browser, but when I take dump of print_r($dataArray); I get only 26 records where as I have around 51 records in total if I run the Query in Query Browser.
You're using mysqli totally wrong.
foreach($results as $result)
is NOT how you fetch data from a query result. You should have
while($row = mysqli_fetch_assoc($result)) {
$dataArray[] = $row;
}
And not to mention the multiple syntax errors in your pasted code...

Categories