So for some reason when I use the = operater in my prepared statement there is no problem however when I use the below operator ( < ) it gives an error.
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given.
So I know mysql gives false if there is a problem with my query. however I cant see the problem.
function availableapps($security)
{
if(empty($databasemanager)) { $databasemanager = new databasemanager(); }
$db = $databasemanager->connectionstring();
$result = $db->prepare("SELECT name FROM applications Where security<?");
$result->bind_param("s", $security);
$result->execute();
$types = array();
while(($row = mysqli_fetch_assoc($result->get_result()))) {
$types[] = $row['name'];
}
$result->close();
return $types;
}
Just for demonstration purposes,
final working code:
function availableapps($security)
{
if(empty($databasemanager)) { $databasemanager = new databasemanager(); }
$db = $databasemanager->connectionstring();
$result = $db->prepare("SELECT name FROM applications Where security<?");
$result->bind_param("s", $security);
$result->execute();
$results = $result->get_result();
$types = array();
while($row = $results->fetch_assoc()) {
$types[] = $row['name'];
}
$result->close();
return $types;
}
while ($row = $result->fetch_assoc()) {
Related
I have this function which returns only one row, How can I modify the function so that it returns more than one row?
public function getVisitors($UserID)
{
$returnValue = array();
$sql = "select * from udtVisitors WHERE UserID = '".$UserID. "'";
$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
There is a function in mysqli to do so, called fetch_all(), so, to answer your question literally, it would be
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ".intval($UserID);
return $this->conn->query($sql)->fetch_all();
}
However, this would not be right because you aren't using prepared statements. So the proper function would be like
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $UserID);
$stmt->execute();
$res = $stmt->get_result();
return $res->fetch_all();
}
I would suggest storing them in an associative array:
$returnValue = array();
while($row = mysqli_fetch_array($result)){
$returnValue[] = array('column1' => $row['column1'], 'column2' => $row['column2']); /* JUST REPLACE NECESSARY COLUMN NAME AND PREFERRED NAME FOR ITS ASSOCIATION WITH THE VALUE */
} /* END OF LOOP */
return $returnValue;
When you call the returned value, you can do something like:
echo $returnValue[0]['column1']; /* CALL THE column1 ON THE FIRST SET OF ARRAY */
echo $returnValue[3]['column2']; /* CALL THE column2 ON THE FOURTH SET OF ARRAY */
You can still call all the values using a loop.
$counter = count($returnValue);
for($x = 0; $x < $counter; $x++){
echo '<br>'.$rowy[$x]['column1'].' - '.$rowy[$x]['column2'];
}
I have a getData() function, and a database with two tables: employers and members.
I would like to pass a variable containing the table name, so inside an "if" I could execute the appropriate SELECT statement. My problem I believe that after the "if" the $stmt->bind_param(); doesn't know which $stmt to bind the take.
Any ideas on how I could achieve this?
Thanks
public function getData($table)
{
if ($table == "employers")
{
$stmt = $this->link->prepare("SELECT * FROM employers ");
}
else
{
$stmt = $this->link->prepare("SELECT * FROM members ");
}
$stmt->bind_param();
if ($stmt->execute())
{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$row = array_map('stripslashes', $row);
$dataArray[] = $row;
}
}
return $dataArray;
}
No, since you aren't binding anything, that ->bind_param method is superfluous. Just take that off.
public function getData($table)
{
$dataArray = array();
$t = ($table === 'employers') ? 'employers' : 'members';
$query = "SELECT * FROM $t";
$stmt = $this->link->prepare($query);
if($stmt->execute()) {
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$row = array_map('stripslashes', $row);
$dataArray[] = $row;
}
}
return $dataArray;
}
Sample Usage:
$data = $aministrator_query->getData('members');
$tbody = '';
foreach($data as $row) {
$tbody .= "<tr><td>{$row['user_id']}</td><td>{$row['user_password']}</td><td>{$row['user_first_name']}</td><td>{$row['user_last_name']}</td></tr>";
}
$table = sprintf('<table><thead><tr><th>ID</th><th>Password</th><th>First Name</th><th>Last Name</th></tr></thead><tbody>%s</tbody></table>', $tbody);
echo $table;
I am getting Fatal error: Cannot pass parameter 3 by reference in line# 4
please suggest me solution I want the binding part dynamic.
$values = array($username,$password);
$query = "select * from users where email_id = ? and password = ?"
$this->con = new mysqli('localhost', 'username', 'password','dbname');
$stmt = $this->con->prepare($query);
$count = 0;
for ($i = 0; $i < count($values); $i++) {
$stmt->bind_param(++$count,$values[$i], PDO::PARAM_STR,12);
}
if ($stmt->execute()) {
while ($row = $this->stmt->fetch()) {
$data[] = $row;
}
return $data;
} else {
return null;
}
use bindValue()
$stmt->bindValue(++$count,$values[$i], PDO::PARAM_STR,12);
I am using same query again and again on different pages in between to fetch result. I want to make a function for this query.
$result = mysql_query(" SELECT name FROM tablename where id= '$row[name_id]'");
$row = mysql_fetch_array($result);
echo $row ['name'];
How to make and how to call the function?
sample class stored sample.php
class sample
{
function getName(id)
{
$result = mysql_query("SELECT name FROM tablename where id='$id'");
$row = mysql_fetch_array($result);
return $row ['name'];
}
}
use page include sample.php,then create object,then call getName() function.
<?php
include "db.class.php";
include "sample.php";
$ob=new sample(); //create object for smaple class
$id=12;
$name=$ob->getName($id); //call function..
?>
This is a good idea but first of all you have to create a function to run queries (as you have to run various queries way more often than a particular one)
function dbget() {
/*
easy to use yet SAFE way of handling mysql queries.
usage: dbget($mode, $query, $param1, $param2,...);
$mode - "dimension" of result:
0 - resource
1 - scalar
2 - row
3 - array of rows
every variable in the query have to be substituted with a placeholder
while the avtual variable have to be listed in the function params
in the same order as placeholders have in the query.
use %d placeholder for the integer values and %s for anything else
*/
$args = func_get_args();
if (count($args) < 2) {
trigger_error("dbget: too few arguments");
return false;
}
$mode = array_shift($args);
$query = array_shift($args);
$query = str_replace("%s","'%s'",$query);
foreach ($args as $key => $val) {
$args[$key] = mysql_real_escape_string($val);
}
$query = vsprintf($query, $args);
if (!$query) return false;
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return false;
}
if ($mode === 0) return $res;
if ($mode === 1) {
if ($row = mysql_fetch_row($res)) return $row[0];
else return NULL;
}
$a = array();
if ($mode === 2) {
if ($row = mysql_fetch_assoc($res)) return $row;
}
if ($mode === 3) {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
then you may create this particular function you are asking for
function get_name_by_id($id){
return dbget("SELECT name FROM tablename where id=%d",$id);
}
You should probably parse the database connection as well
$database_connection = mysql_connect('localhost', 'mysql_user', 'mysql_password');
function get_row_by_id($id, $database_link){
$result = mysql_query("SELECT name FROM tablename where id= '{$id}");
return mysql_fetch_array($result);
}
Usage
$row = get_row_by_id(5, $database_connection);
[EDIT]
Also it would probably help to wrap the function in a class.
function getName($id){
$result = mysql_query("SELECT name FROM tablename where id= '$row[name_id]'");
$row = mysql_fetch_array($result);
return $row ['name'];
}
call the function by
$id = 1; //id number
$name = getName($id);
echo $name; //display name
I would like to return all the results from my prepared query (mysqli) as objects in an array but i cant find a fetchall method or something similar. How do i go about this?
public function getImageResults ($search_term)
{
if (empty($search_term))
return false;
$image_query = $this->db_connection->stmt_init();
$image_query_sql =
"
SELECT
Images.url as url
FROM
Images, ImageSearch, ImageSearchResults
WHERE
ImageSearch.search_string = ? AND
ImageSearchResults.search_id = ImageSearch.id AND
ImageSearchResults.image_id = Images.id AND
Images.deleted = 0 AND
ImageSearch.deleted = 0 AND
ImageSearchResults.deleted = 0
";
if ($image_query->prepare($image_query_sql))
{
$image_query->bind_param('s', $search_term);
$image_query->execute();
$image_query->store_result();
$image_query->bind_result($url);
return //need to return the entire result set here... any ideas?
}
return false;
}
I found this code on the net which kinda works but i get this error when i use it
Notice: Use of undefined constant
mysqli_stmt_bind_result - assumed
'mysqli_stmt_bind_result'
private function getresult ($stmt)
{
$result = array();
$metadata = $stmt->result_metadata();
$fields = $metadata->fetch_fields();
for (;;)
{
$pointers = array();
$row = new stdClass();
$pointers[] = $stmt;
foreach ($fields as $field)
{
$fieldname = $field->name;
$pointers[] = &$row->$fieldname;
}
call_user_func_array(mysqli_stmt_bind_result, $pointers);
if (!$stmt->fetch())
break;
$result[] = $row;
}
$metadata->free();
return $result;
}
The mysqli_stmt_bind_result on this line:
call_user_func_array(mysqli_stmt_bind_result, $pointers);
should be quoted:
call_user_func_array('mysqli_stmt_bind_result', $pointers);
You could also use PDO, an untested example but it should work:
public function getImageResults ($search_term)
{
$sql =
"
SELECT
Images.url as url
FROM
Images, ImageSearch, ImageSearchResults
WHERE
ImageSearch.search_string = ? AND
ImageSearchResults.search_id = ImageSearch.id AND
ImageSearchResults.image_id = Images.id AND
Images.deleted = 0 AND
ImageSearch.deleted = 0 AND
ImageSearchResults.deleted = 0
";
$pdo = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'username', 'password');
$sth = $pdo->prepare($sql);
$sth->execute(array($search_term));
$result = $sth->fetchAll(PDO::FETCH_CLASS, "ArrayObject");
//var_dump($result);//debug
return $result;
}
Hm, you could try something like this, if I remember correctly:
call_user_func_array(array($stmt, 'bind_result'), $pointers);