Executing pre-build-up array with PDO Execute - php

I am trying to pass through any query to a function using PDO.
I have build up the array through a loop function and try to insert it into the execute(array(....)) function, but it's not getting through.
FUNCTION CODE
public function ShowData($sql,$variable)
{
$execute_string = "";
echo "<pre>";
print_r($variable);
echo "</pre>";
$q = $this->conn->prepare($sql);
for($i = 0; $i < sizeof($variable); $i++)
{
if($i != 0) $execute_string .= ",";
$placeholder = $i + 1;
$execute_string .= "':$placeholder' => '".$variable[$i]."'";
}
echo $sql."<br>";
echo $execute_string;
$q->execute(array($execute_string));
echo "<br>Execute Succeeded";
return $row = $q->fetchAll();
}
VIEWPAGE CODE
$author = "Nemoza";
$name = "MBICO_mailer";
$project = $data->ShowData("SELECT * FROM mbico_projects WHERE author=:1 AND name=:2", array($author,$name));
OUTPUT FROM FUNCTION W/ DEBUGGING
Array
(
[0] => Nemoza
[1] => MBICO_mailer
)
SELECT * FROM mbico_projects WHERE author=:1 AND name=:2
':1' => 'Nemoza',':2' => 'MBICO_mailer'
However, the 'Execute Succeeded' text is not being printed, and the execute(array...)) is not actually executing.
What am I doing wrong, and how else should I do it?

here's an example you can use:
public function ShowData($sql,$variable) {
$bind = [];
foreach ($variable as $key => $value) {
$ph = $key+1;
$bind[":" . $ph] = $value;
}
$stmt = $this->conn->prepare($sql);
$stmt->execute($bind);
return $stmt->fetchAll();
}
it's used like this:
$sql = 'select * from users where username = :1 or username = :2';
$bind = ['123', '456'];
$db->ShowData($sql, $bind);
as mentioned in the comments to your question, you need to send an array to execute() function, and not a string.

Managed to do it like this:
public function ShowData($sql,$variable)
{
$execute_string = array();
$q = $this->conn->prepare($sql);
foreach($variable as $item)
{
$execute_string[] = $item;
}
$q->execute($execute_string);
return $q->fetchAll();
}
$project = $data->ShowData("SELECT * FROM mbico_projects WHERE author=? AND title=?", array($author, $title));

Related

Database values with PHP function

I want to call a php function, returns database values.
public function readdata() {
$id = "";
$name = "";
$sth = $db->execute('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
foreach ($sth as $s) {
$id .= $s->id;
$name .= $s->name;
}
return compact('id', 'name');
}
$rd = readdata();
$get_id = $rd['id'];
$get_name = $rd['name'];
echo $get_id;
echo $get_id.$get_name.'<br>';
When I execute the code, it shows the output as:
7891011
7891011Text1Text2Text3Text4Text5
But I want as a single value vertically displayed. Do I need to explode ' | '
I guess you can easily change your existing code slightly and get what you expected,
<?php
public function readdata() {
$id = "";
$name = "";
$sth = $db->execute('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
foreach ($sth as $s) {
$array[$s->id] = $s->name; # building id => name structure
}
return $array;
}
$rd = readdata();
# now readdata() will return data as below array
$array = [7=>'text1',8=>'text2',9=>'text3',10=>'text4',11=>'text5'];
foreach($array as $k=>$v){
$result[] = $k." ".$v;
}
echo implode("\n", $result);
?>
DEMO: https://3v4l.org/PusI4

bind param count first argument

I have the following line:
$formatsArray = $_POST['formats'];
$topicsArray = $_POST['topics'];
// Converting the array into individual strings
$formats = implode(",", $formatsArray);
$topics = implode(",", $topicsArray);
// Prepare the statement
$resources = $con->prepare("SELECT * FROM resources WHERE
(format IN (?))
AND (topic IN (?))");
// Bind the statement
$resources->bind_param('ss',$formats, $topics);
The problem is that topics derived from an array where it could contain multiple string, but 's' will only recognize 1. I would want that if the topic array has 10 entries, than there would be 10s, and same for format.
I have thinking of counting the size of the array and adding an s in every iteration, but not sure how.
Any help would be appreciated.
// Count array
$formatCount = count($formatsArray);
$topicCount = count($topicsArray);
How about this then:
<?php
$con = new mysqli("localhost", "USERNAME", "PASSWORD", "DATABASE");
$formatsArray = array('a','b','c','d',);
$topicsArray = array('x','y','z',);
$sql = 'SELECT * FROM resources WHERE (format IN (FORMAT_REPLACE_ME)) AND (topic IN (TOPIC_REPLACE_ME))';
$formatsPlaceholders = makePlaceHolders($formatsArray);
$topicsPlaceholders = makePlaceHolders($topicsArray);
$sql = str_replace('FORMAT_REPLACE_ME', $formatsPlaceholders, $sql);
$sql = str_replace('TOPIC_REPLACE_ME', $topicsPlaceholders, $sql);
//error_log(print_r($sql,1).' '.__FILE__.' '.__LINE__,0);
try {
$s = $con->prepare($sql);
$vals = array_merge($formatsArray, $topicsArray);
// from http://stackoverflow.com/a/31562035/1814739
$typDfs = str_repeat( 's' , count( $vals ) );
$params = array( $typDfs );
foreach ( $vals as $k => $v ) {
${ 'varvar' . $k } = $v;
$params[] = &${ 'varvar' . $k }; # provide references
}
call_user_func_array( array( $s, 'bind_param' ) , $params );
$s->execute();
$output = array();
$res = $s->get_result();
while ($row = $res->fetch_array(MYSQLI_NUM))
{
//error_log(print_r($row,1).' '.__FILE__.' '.__LINE__,0);
$output []= array(
'id' => $row[0],
'format' => $row[1],
'topic' => $row[2],
);
}
$s->close();
sanitize_output($output);
}
catch (\Exception $e) {
error_log(print_r($e->getMessage(),1).' '.__FILE__.' '.__LINE__,0);
}
function makePlaceHolders($arr){
$ph = '';
for ($i = 1; $i <= count($arr); $i++) {
$ph .= '?,';
}
return rtrim($ph,',');
}
function sanitize_output(array &$arr, array $args=array()) {
array_walk_recursive($arr,'so',$args);
}
function so(&$v,$k,$args) {
$excludes = isset($args['excludes']) ? $args['excludes'] : array();
if (!in_array($k,$excludes)) {
$v = trim($v);
$v = (get_magic_quotes_gpc()) ? stripcslashes($v) : $v;
$v = htmlspecialchars($v);
}
}
?>
<html>
<body>
<ul>
<?php foreach($output as $k => $o) { ?>
<li><?php echo $o['id']; echo $o['format']; echo $o['topic']; ?></li>
<?php } ?>
</ul>
</body>
</html>

return array in function

I want to translate each words in array:
$myarray = array("hi","bro");
So I wrote a translate function like this:
function translate($word) {
foreach ( $word as $key_translate ) {
$array = array();
$sql = mysql_query("SELECT * FROM `translate` WHERE name = '".$key_translate."' ");
if ( mysql_num_rows($sql) == 1 ) {
$row = mysql_fetch_array($sql);
$name = $row['fa_name'];
return $name;
//retuen array($name);
}
else {
return $key_translate;
//return array($key_translate);
}
}
}
And using this to show translated array:
print_r (translate($myarray));
But it's not returning array, it's just showing first key as string.
How can I return array in function?
Don't return inside the loop, that exits the whole function immediately and just returns that one element. Accumulate the results in an array, and return that.
function translate($word) {
$result = array();
foreach ( $word as $key_translate ) {
$sql = mysql_query("SELECT fa_name FROM `translate` WHERE name = '".$key_translate."' ");
if ( mysql_num_rows($sql) == 1 ) {
$row = mysql_fetch_array($sql);
$result[] = $row['fa_name'];
}
else {
$result[] = $key_translate;
}
}
return $result;
}
Also, there's no reason to use SELECT * if you're only interested in fa_name.
Try this:
function translate($word) {
foreach ($word as $key => $translate) {
$sql = mysql_query("SELECT * FROM `translate` WHERE name = '" . $translate . "' ");
if (mysql_num_rows($sql) == 1) {
$row = mysql_fetch_array($sql);
$word[$key] = $row['fa_name'];
}
}
return $word;
}

PHP OOP not passing variables in the class

I have a PHP class that is meant to get a mysqli query, make a multidimensional array, and currently just echo the whole array. It is this code:
include("connect.php");
class database
{
public $motto;
public $motto_array = array();
public $rating;
public $rating_array = array();
public $category;
public $score;
private $mysqli;
public $counter_array = array();
public $multi_dim_values = array();
public $multi_dim_category = array();
function setMysqli($mysqli)
{
$this->mysqli = $mysqli;
}
function setCategory($category)
{
$this->category = $category;
}
function query_category()
{
if ($stmt = $this->mysqli->prepare("SELECT motto, score FROM mottos WHERE category=? ORDER BY score DESC"))
{
$stmt->bind_param("s", $this->category);
$stmt->execute();
$stmt->bind_result($motto, $ranking);
while ( $stmt->fetch() ) {
$this->motto_array[] = $motto;
$this->rating_array[] = $ranking;
}
$stmt->close();
}
}
function multi_dim_array()
{
$multi_dim_values = array($this->motto_array, $this->rating_array);
$counter_array = range(0,count($this->motto_array)-1);
foreach($counter_array as $index => $key) {
$foreach_array = array();
foreach($multi_dim_values as $value) {
$foreach_array[] = $value[$index];
}
$multi_dim_category[$key] = $foreach_array;
}
return $multi_dim_category;
}
}
$class = new database;
$class->SetMysqli($mysqli);
$class->SetCategory("person");
$class->query_category();
print_r($class->multi_dim_array);
print_r($class->multi_dim_category);
connect.php has the database connection information for the mysqli.
I am learning OOP, so I did this in procedural, and it works fine, with this code:
include("connect.php");
function category($mysqli, $cat)
{
if ($stmt = $mysqli->prepare("SELECT motto, score FROM mottos WHERE category=? ORDER BY score DESC"))
{
$stmt->bind_param("s", $cat);
$stmt->execute();
while($stmt->fetch())
{
printf ("[%s (%s) in %s] \n", $motto, $ranking, $category);
$array .= compact("motto", "category", "ranking");
}
print_r($array);*/
$a = array();
$b = array();
$c = array();
$stmt->bind_result($motto, $ranking);
while ( $stmt->fetch() ) {
$a[] = $motto;
$b[] = $ranking;
}
$result = array();
$values = array($a, $b);
$c = range(0,count($a)-1);
foreach($c as $index => $key) {
$t = array();
foreach($values as $value) {
$t[] = $value[$index];
}
$result[$key] = $t;
}
return $result;
$stmt->close();
}
}
$cat = "person";
$array_one = category($mysqli, $cat);
print_r($array_one);
This prints the multidimensional array just like I want it to.
What am I doing wrong in the OOP code?
Thank you.
Your code:
print_r($class->multi_dim_array);
You forgot the (), so you're not invoking the method. You're accessing a (non-existent) property. Try this:
print_r($class->multi_dim_array());

Mysqli get_result alternative

I've just changed all my sql queries to prepared statements using mysqli. To speed this process up I created a function (called performQuery) which replaces mysql_query. It takes the query, the bindings (like "sdss") and the variables to pass in, this then does all the perpared statement stuff. This meant changing all my old code was easy. My function returns a mysqli_result object using mysqli get_result().
This meant I could change my old code from:
$query = "SELECT x FROM y WHERE z = $var";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)){
echo $row['x'];
}
to
$query = "SELECT x FROM y WHERE z = ?";
$result = performQuery($query,"s",$var);
while ($row = mysql_fetch_assoc($result)){
echo $row['x'];
}
This works fine on localhost, but my web hosting server does not have mysqlnd available, therefore get_result() does not work. Installing mysqlnd is not an option.
What is the best way to go from here? Can I create a function which replaces get_result(), and how?
Here is a neater solution based on the same principle as lx answer:
function get_result( $Statement ) {
$RESULT = array();
$Statement->store_result();
for ( $i = 0; $i < $Statement->num_rows; $i++ ) {
$Metadata = $Statement->result_metadata();
$PARAMS = array();
while ( $Field = $Metadata->fetch_field() ) {
$PARAMS[] = &$RESULT[ $i ][ $Field->name ];
}
call_user_func_array( array( $Statement, 'bind_result' ), $PARAMS );
$Statement->fetch();
}
return $RESULT;
}
With mysqlnd you would normally do:
$Statement = $Database->prepare( 'SELECT x FROM y WHERE z = ?' );
$Statement->bind_param( 's', $z );
$Statement->execute();
$Result = $Statement->get_result();
while ( $DATA = $Result->fetch_array() ) {
// Do stuff with the data
}
And without mysqlnd:
$Statement = $Database->prepare( 'SELECT x FROM y WHERE z = ?' );
$Statement->bind_param( 's', $z );
$Statement->execute();
$RESULT = get_result( $Statement );
while ( $DATA = array_shift( $RESULT ) ) {
// Do stuff with the data
}
So the usage and syntax are almost identical. The main difference is that the replacement function returns a result array, rather than a result object.
I encountered the same problem and solved it using the code provided in the answer of
What's wrong with mysqli::get_result?
My function looks like this now (error handling stripped out for clarity):
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)
{
$ret = FALSE;
$stmt = $db->prepare($query);
call_user_func_array(array($stmt,'bind_param'),
array_merge(array($types), $params));
$stmt->execute();
$result = array();
if (db_bind_array($stmt, $result) !== FALSE) {
$ret = array($stmt, $result);
}
$stmt->close();
return $ret;
}
Usage like this:
$userId = $_GET['uid'];
$sql = 'SELECT name, mail FROM users WHERE user_id = ?';
if (($qryRes = db_query($db, $sql, 'd', array(&$userId))) !== FALSE) {
$stmt = $qryRes[0];
$row = $qryRes[1];
while ($stmt->fetch()) {
echo '<p>Name: '.$row['name'].'<br>'
.'Mail: '.$row['mail'].'</p>';
}
$stmt->close();
}
I found the anonymous advice posted as a note at the API documentation page for mysqli_stmt::get_result very useful (I couldn't think of a better way than the eval trick), as we very often want to fetch_array() on our result. However, because I wanted to cater for a generic database object, I found it a problem that the code assumed numeric array was fine for all callsites, and I needed to cater for all callers using assoc arrays exclusively. I came up with this:
class IImysqli_result {
public $stmt, $ncols;
}
class DBObject {
function iimysqli_get_result($stmt) {
$metadata = $stmt->result_metadata();
$ret = new IImysqli_result;
if (!$ret || !$metadata) return NULL; //the latter because this gets called whether we are adding/updating as well as returning
$ret->ncols = $metadata->field_count;
$ret->stmt = $stmt;
$metadata->free_result();
return $ret;
}
//this mimics mysqli_fetch_array by returning a new row each time until exhausted
function iimysqli_result_fetch_array(&$result) {
$stmt = $result->stmt;
$stmt->store_result();
$resultkeys = array();
$thisName = "";
for ( $i = 0; $i < $stmt->num_rows; $i++ ) {
$metadata = $stmt->result_metadata();
while ( $field = $metadata->fetch_field() ) {
$thisName = $field->name;
$resultkeys[] = $thisName;
}
}
$ret = array();
$code = "return mysqli_stmt_bind_result(\$result->stmt ";
for ($i=0; $i<$result->ncols; $i++) {
$ret[$i] = NULL;
$theValue = $resultkeys[$i];
$code .= ", \$ret['$theValue']";
}
$code .= ");";
if (!eval($code)) {
return NULL;
}
// This should advance the "$stmt" cursor.
if (!mysqli_stmt_fetch($result->stmt)) {
return NULL;
}
// Return the array we built.
return $ret;
}
}

Categories