Prepared application method.

I do not know what is missing or why it does not display data. My code works if I do not use prepared statements. When I used prepared statements, it seems that the code no longer works.

db.php

Class Database{ public $mysqli; public function __construct($db_host, $db_user, $db_password, $db_name){ $this->con = new mysqli($db_host, $db_user, $db_password, $db_name); } public function selectUserInfo($id){ $stmt = $this->con->prepare("SELECT * FROM users WHERE os_id = ?"); $stmt->bind_param("s", $id); if($stmt->execute() == FALSE){ trigger_error($stmt->error, E_USER_ERROR); }else{ $data = array(); while($row = $stmt->fetch()){ $data[] = $row; } return $data; } } } 

config.php

 define("DBHOST","somehost"); define("DBUSER","someroot"); define("DBPASS","somepassword"); define("DB","my_database"); 

this is how i would display it on my page.

 require 'global/db.php'; require_once 'config.php'; $db = new Database(DBHOST, DBUSER, DBPASS, DB); $data = $db->selectUserInfo($_GET['name']); foreach ($data as $key) { # code... echo $key['os_fname']; } 
-one
source share
2 answers

As we determined, the problem was in your foreach .

The way you read it is wrong, fetch does not have associative properties, so you need to use bind_result .

Here is the hack that is also offered in the fetch manual :

 public function selectUserInfo($id) { $stmt = $this->con->prepare("SELECT * FROM users WHERE os_id=?"); $stmt->bind_param('i', $id); if(!$stmt->execute()) { trigger_error($stmt->error, E_USER_ERROR); } else { $bindVarArray = array(); $data = array(); $result; $meta = $stmt->result_metadata(); while ($column = $meta->fetch_field()) { $columnName = str_replace(' ', '_', $column->name); $bindVarArray[] = &$result[$columnName]; } call_user_func_array(array($stmt, 'bind_result'), $bindVarArray); $index = 0; while ($stmt->fetch() != null) { foreach ($result as $k => $v) { $data[$index][$k] = $v; } $index++; } return $data; } } 

Then you can use your foreach to read it like this:

 foreach ($data as $result) { echo $result['os_fname'], ' => ', $result['os_lname'], "\n"; } 

And you can always use print_r to find out how the resulting array is:

 print_r($data); 
0
source

Is your od_id type in the DB a string or an integer? if an integer

 public function selectUserInfo($id){ $stmt = $this->con->prepare("SELECT * FROM users WHERE os_id = ?"); $stmt->bind_param("i", $id);//use 'i' instead of 's' if($stmt->execute() == FALSE){ trigger_error($stmt->error, E_USER_ERROR); }else{ $data = array(); while($row = $stmt->fetch()){ $data[] = $row; } return $data; } 

}

-3
source

Source: https://habr.com/ru/post/1501206/


All Articles