I have the following function:
public function detail($detail, $table, $column, $value) {
if(is_array($detail)) {
$data = array();
foreach($detail as $key) {
$stmt = $this->mysqli->prepare("SELECT `$key` FROM `$table` WHERE `$column` = ?");
if(is_numeric($value)) {
$stmt->bind_param('i', $value);
} else {
$stmt->bind_param('s', $value);
}
$stmt->execute();
$stmt->bind_result($detail);
$stmt->fetch();
$data[] = $detail;
}
return $data;
} else {
$stmt = $this->mysqli->prepare("SELECT `$detail` FROM `$table` WHERE `$column` = ?");
if(is_numeric($value)) {
$stmt->bind_param('i', $value);
} else {
$stmt->bind_param('s', $value);
}
$stmt->execute();
$stmt->bind_result($detail);
$stmt->fetch();
return $detail;
}
}
This functions works well untill I use an array. The way to use this function is something like this: $db->detail('username', 'users', 'id', 1) This would return the username from users where the id is 1 (this works fine). Like I said the problem starts when I use an array so for example:
$details = array('username', 'active', 'registered');
$details = $db->detail($details, 'users', 'id', 1);
print_r($details);
The error is pointing to $stmt->bind_param('i', $value); in the if(is_array()). I already tried the answer of: bind_param on a non-object but that didn't help me; I still get the same error.
I hope someone knows how to fix the Fatal error: Call to a member function bind_param() on a non-object error for me.
Thanks in advance.
Try to unset the $stmt variable in the loop:
public function detail($detail, $table, $column, $value) {
if(is_array($detail)) {
$data = array();
foreach($detail as $key) {
$stmt = $this->mysqli->prepare("SELECT `$key` FROM `$table` WHERE `$column` = ?");
if(is_numeric($value)) {
$stmt->bind_param('i', $value);
} else {
$stmt->bind_param('s', $value);
}
$stmt->execute();
$stmt->bind_result($detail);
$stmt->fetch();
$data[] = $detail;
$stmt = null;
}
return $data;
} else {
$stmt = $this->mysqli->prepare("SELECT `$detail` FROM `$table` WHERE `$column` = ?");
if(is_numeric($value)) {
$stmt->bind_param('i', $value);
} else {
$stmt->bind_param('s', $value);
}
$stmt->execute();
$stmt->bind_result($detail);
$stmt->fetch();
return $detail;
}
}
This should help.
I think the efficient way to prepare query without using loop is too implode values in the array instead of looping and preparing the query statement.
For eg:- if the query is
SELECT `username`,`active`,`register` FROM users WHERE ID = 1 //username,active and register can be used in single prepare statement by imploding the array
if(is_array($detail)) {
$data = array();
$stmt = $this->mysqli->prepare("SELECT ".implode(", ",$detail)." FROM `$table` WHERE `$column` = ?");
if(is_numeric($value)) {
$stmt->bind_param('i', $value);
} else {
$stmt->bind_param('s', $value);
}
$stmt->execute();
$stmt->bind_result($detail);
$stmt->fetch();
$data[] = $detail;
$stmt = null;
return $data;
}
Related
I just thought about this case and how to do it a bit more "professional". Does not seem to as if this the way to go even though I do not know any other. Somebody?!
$query = "SELECT col1 FROM ".PREFIX."table WHERE (col2 = :something)";
$stmt = $dbh->prepare($query);
$stmt->bindParam(":something", $something, PDO::PARAM_STR);
$stmt->execute();
$stmt->bindColumn(1, $col1, PDO::PARAM_STR);
/* get number of rows */
$num_rows = $dbh->query("SELECT FOUND_ROWS()")->fetchColumn();
if($num_rows == 1) {
$stmt->fetch();
$result = $col1;
} else {
while($stmt->fetch()) {
$result[] = $col1;
}
}
i got two methods.one method is to insert data and the other one is to get the id of the inserted data. i tried several test but it doesn't give any return value.is it possible to pass a return value from another method?
public function insertRegistrantInfo($fname, $lname) {
$query = $this->db->prepare("INSERT INTO `registrants_info` (`first_name`, `last_name`) VALUES (?,?)");
$query->bindValue(1, $fname);
$query->bindValue(2, $lname);
try {
$row = $query->execute();
//$log = $this->getSessionID($email);
return $this->getSessionID($email);
#mail function can be added here
}catch(PDOException $e) {
die($e->getMessage());
}
}
public function getSessionID($email) {
try {
//global $bcrypt;
$query = $this->db->prepare("SELECT `id` FROM `registrants_info` WHERE `email` = ?");
$query->bindValue(1, $email);
$query->execute();
$data1 = $query->fetch();
$id = $data1['id'];
//echo $id;
return $id;
} catch(PDOException $e) {
die($e->getMessage());
}
}
and the returning page is here:
if($data = $admin->insertRegistrantInfo($fname, $lname) == true) {
session_regenerate_id(true);
$_SESSION['id'] = $data;
//print_r($_SESSION);
header('location: registry.php');
exit();
}
Use the lastInsertID() method on your query object rather than a second query
public function insertRegistrantInfo($fname, $lname) {
$query = $this->db->prepare("INSERT INTO `registrants_info` (`first_name`, `last_name`) VALUES (?,?)");
$query->bindValue(1, $fname);
$query->bindValue(2, $lname);
try {
$row = $query->execute();
$insertId = $query->lastInsertId(); // <!-- Use this instead of a second query
#mail function can be added here
}catch(PDOException $e) {
die($e->getMessage());
}
}
Its also important to note that you are not inserting the 'email address' into your database, so there is no way for the query to find it by that field if you were to use another SELECT statement. You might want to complete your INSERT statement.
I don't know what's missing or why it isn't displaying data. My code is working if I'm not using prepared statements. When I used prepared statements, it seems that code is not working anymore.
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 displayed it at 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'];
}
As we have defined, that the issue was with your foreach.
What is wrong is with how you're reading it, fetch does not have associative properties so need to use the bind_result.
Here is a hack that is also suggested at 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 see how your resulting array is:
print_r($data);
your od_id type in DB is string or integer? if a 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;
}
}
SELECT * FROM `ware_house_indents` WHERE `has_cancel` = ? AND `eid`= ?
i need to get result above query in mysqli. but i cant use get_result() function because it is not working in server.i have found this below function and it is working fine.but that function not possible to pass multiple parameters.please help me to solve this problem.
function db_bind_array($stmt, &$row)
{
$md = $stmt->result_metadata();
$params = array();
while($field = $md->fetch_field()) {
$params[] = &$row[$field->name];
}
return call_user_func_array(array($stmt, 'bind_result'), $params);
}
function db_query($db, $query, $types, $params)
{
$stmt = $db->prepare($query);
$bindRet = call_user_func_array(array($stmt,'bind_param'),
array_merge(array($types), $params));
$stmt->execute();
$result = array();
if (db_bind_array($stmt, $result) !== FALSE) {
return array($stmt, $result);
}
$stmt->close();
return FALSE;
}
if (($qryRes = db_query($mysqli, $sql, 'i', array(&$var))) !== FALSE) {
$stmt = $qryRes[0];
$row = $qryRes[1];
while ($stmt->fetch()) {
print_r($row);
}
$stmt->close();
}
Let me suggest you a quite indirect solution.
You'd do yourself a huge favor if start using PDO instead of mysqli
It has no mysqli disadvantages when dealing with prepared statements as it has a way better implementation of above functions out of the box. So, it will let you to get your data in a few lines:
$sql = "SELECT * FROM ware_house_indents WHERE has_cancel = ? AND eid= ?";
$stm = $pdo->prepare($sql);
$stm->execute(array($cancel,$eid));
$data = $stm->fetchAll(); // or fetch() if you need only one row
that's all
I've been searching the internet for a while now, but since I'm new to MySQLi, I cannot solve this problem myself. This is my code so far. I want to return the result as an array.
function myFunction($u_id, $mysqli){
$userinfo = "SELECT email, name, street, placename FROM users WHERE u_id = ? LIMIT 1";
if($stmt = $mysqli->prepare($userinfo)) {
$stmt->bind_param('i', $u_id);
$stmt->execute();
if(!$stmt->execute()) {
echo $stmt->error.' in query: '.$userinfo;
} else {
//this is what i found somewhere on the internet, and it gives me an array with the right keys but empty values.
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$parameters[$var] = &$$var;
}
return $parameters;
}
$stmt->close();
}}
Hopefully someone can help me get this code working, or help me find an alternative.
Have you looked at using fetch_array
http://php.net/manual/en/mysqli-result.fetch-array.php
Working from your code
function myFunction($u_id, $mysqli){
$userinfo = "SELECT email, name, street, placename FROM users WHERE u_id = ? LIMIT 1";
if($stmt = $mysqli->prepare($userinfo))
{
$stmt->bind_param('i', $u_id);
$stmt->execute();
if(!$stmt->execute())
{
echo $stmt->error.' in query: '.$userinfo;
}
else {
//this is what i found somewhere on the internet, and it gives me an array with the right keys but empty values.
$parameters = array();
while ($row = $stmt->fetch_assoc()) {
$parameters[] = $row;
}
$stmt->close();
return $parameters;
}
$stmt->close();
}
}