Rick James
Rick James

Reputation: 141

php sanitize output form array

I have an array that takes data from a mysql query.

$mysql = "select distinct name from software";
$result = mysqli_query($conn, $mysql);
    while($myrow = mysqli_fetch_assoc($result)) {
      $array[] = $myrow;
}

What I would like to do is to have the data output like:

item1, item2, item3

In the end what I want to do is to be able to store that info in a variable to use for a mysql query

$array = item1, item2, item3

select * from table where item != ($array)

However I cannot get the data to output correctly,

If I use print_r the data is shown and the array is good.

If i use array_key() I only get the numbers, how can I get the names?

print_r output:

( [0] => Array ( [name] => Skype for Business Basic 2016 - en-us ) [1] => Array ( [name] => Microsoft Visual C++ 2008 Redistributable - x64 9. ) [2] => Array ( [name] => Microsoft Office 365 Business - en-us ) [3] => Array ( [name] => Microsoft Silverlight ) [4] => Array ( [name] => NVIDIA 3D Vision Driver 341.92 ) [5] => Array ( [name] => NVIDIA Graphics Driver 341.92 ) [6] => Array ( [name] => NVIDIA Update 10.4.0 ) [7] => Array ( [name] => NVIDIA HD Audio Driver 1.3.30.1 ) [8] => Array ( [name] => FortiClient ) ) 

Upvotes: 1

Views: 178

Answers (3)

Ben Holness
Ben Holness

Reputation: 2707

Are you just using the output for the second query and nothing else? If so then why store it in an array? Instead you could do something like

$namelist = "";
$mysql = "select distinct name from software";
$result = mysqli_query($conn, $mysql);
while($myrow = mysqli_fetch_assoc($result)) {
  $namelist .= mysqli_real_escape_string($conn, $myrow['name']).",";
}
$namelist = substr($namelist, 0, -1);

Then it's directly ready for the second query, which will need a NOT IN:

select * from table where item NOT IN ($array)

Note that it's better practice to use prepared statements over mysqli_real_escape_string, but in this case it should be fine as $namelist comes directly from your database already.

Upvotes: 0

Blablaenzo
Blablaenzo

Reputation: 1057

You can use array_column (PHP 5.5+) to get the values you want:

print_r(array_column($array, 'name'));

Upvotes: 0

Don't Panic
Don't Panic

Reputation: 41810

When you do this:

while($myrow = mysqli_fetch_assoc($result)) {
    $array[] = $myrow;
}

You are appending the entire row array to $array for each row you fetch. You can change it to

while($myrow = mysqli_fetch_assoc($result)) {
    $array[] = $myrow['name'];
}

to only append the name string. Then you will have an array of strings rather than an array of arrays, and implode will give you the results you expect.

Upvotes: 1

Related Questions