Mohammed Mohammed - 10 months ago 59
PHP Question

Echo full array from sql

Am trying to get data from SQL that match a specific word so I wrote this code for it

require ('config.php');
$searchphrase = $_GET['seach'];
$searcharry = explode(" ", $searchphrase);
$searcharrycount = count($searcharry);
$i1 = 0;
$i2 = 0;
while ( $i1 < $searcharrycount) {
$sql = "SELECT word, url FROM words WHERE word LIKE '%$searcharry[$i1]%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$url = explode(" , ", $row["url"]);
$urlcount = count($url);
while ($i2<$urlcount) {
echo $url[$i2]."<br>";


//end sql


and this is how my SQL is designed

SQL data stracture

So when I run this code I expect to get results like the flowing







However, I get the flowing results when I run the code:





So my question is how can I show the output that I expect rather than showing two of every row in SQL?

Answer Source

You never reset $i2, so as you process more rows of database results, $i2 keeps growing, and you eventually start using indexes that DON'T EXIST. E.g. let's say ever row of your DB contains 3 urls.

row1: url1,url2,url3
row2: url4,url5,url6
row3: url7,url8,url9

Since you never reset $i2, you end up doing:

row1: url1,url2,url3
  i2    0   1     2

row2: url4,url5,url6
  i2:                 3   4   5

row3: url7,url8,url9
  i2:                             6   7   8

Either put a $i2=0 before your while() loop, so you always start with index 0, or simply get rid of that (pointless) while loop entirely:

echo str_replace(' , ', '<br>', $row['url']);

Since all you're doing, really, is changing that comma to a break, might as well change ALL of them at the same time.