Page 1 of 1

Get array with ID and Users from database

Posted: 28 Oct 2018, 07:56
by JanMolendijk
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`

Retrieve list from database

Posted: 28 Oct 2018, 09:11
by JanMolendijk
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']];
  }
}