I am getting so frustrated with this. I am trying to make an array containing the values of a column using mysqli. Right now when i echo what is returned it is printing nothing. I have tried so many things i can not figure this out.
<?php
class Database {
public $dbHost = '';
public $dbUser = '';
public $dbPass = '';
public $dbName = '';
public $db;
public function __construct(){
$this->dbConnect();
}
public function dbConnect(){
$this->db = new mysqli($this->dbHost, $this->dbUser, $this->dbPass, $this->dbName);
/* check connection */
if (mysqli_connect_errno()){
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}else{
echo 'connection made';
}
}
public function q($sql){
$query = $sql;
self::preparedStatement($query);
}
public function preparedStatement($query){
$i= 0; //index
$result = array();
if ($stmt = $this->db->prepare($query)){
/* execute statement */
if($stmt->execute()) {
$stmt->bind_result($name);
while($stmt->fetch()) {
$result[0] = $name;
}
} else
echo "error";
/* close statement */
$stmt->close();
} else {
echo "Prepare failed: (" . $stmt->errno . ") " . $stmt->error;
}
return $result;
}
public function __destruct(){}
}
### Test code
$db = new Database();
$res = $db->q("SELECT name FROM test");
echo $res[0];
?>
first of all, remove the
0in yourwhileloop. You want the values to be stored in an array one after the other, what you’re doing is always overwriting the first value in the array, and you need to store the value you get fromfetch()in a temporary array.second, you need your
q()function to return some value, so change the last statement toPlease spend some time Googling about this and looking at examples of how other people are doing it.