简体   繁体   中英

How can I create an array with all rows from database

Hi is there any way I could loop throw my rows in DB and if the value Popular is = 1 assign its id to an array? Basically I need to cycle thru my products table and assign all id of rows that product is = 1 to an array so I can use it later in my HTML. I'm using PHP7

Here is what I tried to achieve this:

//Variables
  $Host = 'localhost';
  $UserName = 'root';
  $Password = 'NOP';
  $DataBaseName = 'BoosTemplatesDB';
  $DEBUG = True;

  $link = mysqli_connect($Host, $UserName, $Password, $DataBaseName);

  // If the script cant connect to DB it will redirect to 409 error page and exit.
  if (mysqli_connect_error()) {
    if ($DEBUG == True) {
      die ('MySQL error trying to connect to host '.mysqli_connect_error());
    } else {
      header("Location: http://127.0.0.1/409.html");
      exit();
    }
  }

  $query_products = 'SELECT * FROM Products';
  $result = $link->query($query_products);

  if ($result->num_rows > 0) {

    $Popular = array();

    while($row != 4) {
        if ($row['Popular'] == 1) {
          $value = $row['ID'];
          array_push($Popular,$value);
        }
    }
    echo $value;
  } else {
    if ($DEBUG == True) {
      die ('MySQL couldnt find any result for the query: '.$query_products);
    } else {
      header("Location: http://127.0.0.1/409.html");
      exit();
    }
  }

$link->close();

My DB: 在此处输入图片说明

Instead of checking the value of Popular on PHP side, you can filter directly your rows like this, and return the list of ID directly

SELECT ID FROM Products WHERE Popular = 1;

Then, you can use mysqli_fetch_array to get the results as an array directly

while ($row = mysqli_fetch_array($result)) {
  $Popular[] = $row;
}

print_r($Popular)

Im using this mysqli syntax, i think its simpler than the one youre using

$mysqli = new mysqli($Host, $UserName, $Password, $DataBaseName);
if (mysqli_connect_errno()) {
    printf("Connexion error : %s\n", mysqli_connect_error());
    exit();
}
$mysqli->query("SET NAMES utf8");
$query = 'SELECT  * FROM Products';
$result = $mysqli->query($query);
while ($row = $result->fetch_array()) {
     if(row['Popular']==1) { 
          //do your thing with row['ID'] 
     }
}

Also, why do you not simply make the request "SELECT ID from products where Popular = 1" ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM