Get array with ID and Users from database

Discuss coding issues, and scripts related to PHP and MySQL.
User avatar
JanMolendijk
Posts: 282
Location: Holland Rotterdam

Get array with ID and Users from database

Without real knowledge the gambling remains & questions arise
& without the support from Coursesweb it is checkmate for me :D

I found a script where I`m able to tag people
but I don`t have any cluw how to retrieve a list from a database ???

Code: Select all

<?php
$term = isset($_GET['term']) ? $_GET['term'] : '';

//TODO: you should retrieve this list from database

//list of users

$allUsers = array(
	array('id' => 10 , 'title' => ' molendijk '),
	array('id' => 20 , 'title' => ' rotterdam '),
);

$users = array();
foreach ($allUsers as $user)
{
	if (stripos($user['title'], $term ) !== false) {
		$users[] = $user;
	}
}

//generate output
echo json_encode($users);
?>

On the line //TODO: you should retrieve this list from database
I tried simple this code to complete but it is not working

Code: Select all

<?php
// connect to the "tests" database
$conn = new mysqli('127.0.0.1', 'comments', '123456', 'comments');
// check connection
if (mysqli_connect_errno()) {
  exit('Connect failed: '. mysqli_connect_error());
}
// SELECT sql query
$sql = "SELECT * FROM `user`  ORDER BY `id` DESC"; 
// perform the query and store the result
$result = $conn->query($sql);
// if the $result contains at least one row
if ($result->num_rows > 0) {
  // output data of each row from $result
  while($row = $result->fetch_assoc()) {
//list of users I tried to add $row
$allUsers = array(
	array('id' => '. $row['id']. ' , 'title' => ' '. $row['user']. ' '),
	array('id' => '. $row['id']. ' , 'title' => ' '. $row['user']. ' '),
I hope you have some ideas for me `thanks in advanced`

JanMolendijk Posts: 282
I found the answer:

Code: Select all

// SELECT sql query
$sql = "SELECT * FROM `user`  ORDER BY `id` DESC";

// perform the query and store the result
$result = $conn->query($sql);
$allUsers =[];

// if the $result contains at least one row
if($result->num_rows > 0){
  // output data of each row from $result
  while($row = $result->fetch_assoc()){
    //list of users I tried to add $row
    $allUsers[] =['id'=>$row['id'], 'title'=>$row['user']];
  }
}

Similar Topics