What is the proper way to create a function to get array values from a query? I am getting "Undefined index: page_title" error.
However I can get the value without function like: echo $row->page_title;
Or echo $query[0]->title;
function get_page($id) {
$db = new DB();
$query = $db->get_rows("SELECT * FROM pages WHERE id = :id ", array('id' => $_GET['id']) );
foreach ($query as $row) {
$page_id = $row->id;
$page_title = $row->title;
}
return $query;
}
$page = get_page(1);
echo $page['page_title'];
here is my database class:
function get_rows($query, $values=array(), $fetchType = FETCH_OBJ)
{
$sth = $this->dbh->prepare($query);
if(is_array($values) && (sizeof($values) > 0))
{
foreach($values as $key=>$val)
{
$key = is_numeric($key) ? ($key + 1) : $key;
$sth->bindValue($key,$val);
}
}
if($sth->execute())
return $sth->fetchAll($fetchType);
}
To make the function reusable, I would rewrite it the following way
function get_page($id, $col) {
$db = new DB();
$query = $db->prepare('SELECT * FROM pages WHERE id = :id');
$query->execute(array(':id' => $id));
$results = $query->fetch(PDO::FETCH_NUM);
return $results[0][$col];
}
$page = get_page(1, 'page_title');
echo $page;
I skipped the foreach as you said that all id's are unique so you should only ever have 1 result
Also it may not be a bad idea to add some error checking to make sure you do get back what you expect from the query and to make sure it is not empty.
Edit: Sorry if the syntax is a little off, dont have anything to test the code against quickly.
Related
I have got this code:
function retrieve_answers($array = array(), $id = null)
{
include(root_path . '\config.php');
if($id == null)
{
$id = $this->question_id;
}
$query = mysqli_query($link, "SELECT * FROM `answers` WHERE `question_id`='$id'");
if(!mysqli_num_rows($query))
{
throw new Exception('Question not found.');
}
/* - Retrieves the answer rows
- Loops through the array
- Indexes the array and assigns the answerID to the index */
else
{
while($result = mysqli_fetch_array($query))
{
for($i=0;$i<mysqli_num_rows($query);$i++)
{
$array[$i] = $result["id"];
}
}
}
}
Which is a part of a class.
What am I trying to do?
I am trying to accept an array as a parameter, and assign values to the array, the values are to be answerIDs which are linked to the question.
The test.php file is here:
<?php
define('root_path', realpath(dirname(__FILE__)));
include(root_path . '\config.php');
require_once(root_path . '\includes\question.class.php');
$q = new Question(3);
$array = array();
$q->retrieve_answers($array);
var_dump($array);
?>
What happens?
When I try to debug by dumping the array, it shows that the array contains nothing:
array(0) { }
I tried to execute the MySQL result through the class to debug, and it does succeed to retrieve the answer IDs, so I'm pretty positive the issue is in the array.
I would happy to get assistance, thanks in advance.
return value in a function like this
function retrieve_answers($array = array(), $id = null)
{
include(root_path . '\config.php');
if($id == null)
{
$id = $this->question_id;
}
$query = mysqli_query($link, "SELECT * FROM `answers` WHERE `question_id`='$id'");
if(!mysqli_num_rows($query))
{
throw new Exception('Question not found.');
}
/* - Retrieves the answer rows
- Loops through the array
- Indexes the array and assigns the answerID to the index */
else
{
$i = 0;
while($result = mysqli_fetch_array($query))
{
$array[$i] = $result["id"];
$i++;
}
return $array;
}
}
and then get it as
$arr = $q->retrieve_answers($array);
var_dump($arr);
I'm trying to build a re-usable function to multidimansional array for every tablename i put in.
Like most i start mine tables whit ID and want to start the array whit that id, so not start whit 0 :) . foneticly--> $my_array[id]["email"]
So to build it i thought "what do i need" and found : $count_colum, $total_row an ofcource the data itself.
I know how to build a array, but i dont know how to build a "variable" array.
I also know i cant use PHP inside a array :) (whish would help iff you tell me)
$my_array = array( $row['id'] for ($i = 0; $i < $count_colum; $i++){...}
I also hope somebody knows what i mean :) I'm a little bit new to this all ;)
This is what i get this far:
function make_MDA($tablename)
{
$dbh = new PDO("mysql:host='localhost';dbname='dbname', 'usr','pas'");
$query = $dbh->prepare("SELECT * FROM `".$tablename."`");
$query->execute();
$count_colum = $query->columnCount();
$result = $query->fetchAll();
$total_row = count($result);
for ($i = 0; $i < $count_colum; $i++)
{
$meta = $query->getColumnMeta($i);
$column[] = $meta['name'];
}
foreach ($result as $row)
{
$my_array = array( $row['id'] //this is where I'm stuck
}
// echo $column[3];
// echo $total_row;
// echo $count_colum;
}
This should work, don't overcomplicate things:
function make_MDA($tablename)
{
$dbh = new PDO("mysql:host='localhost';dbname='dbname', 'usr','pas'");
$query = $dbh->prepare("SELECT * FROM `".$tablename."`");
$query->execute();
$result = $query->fetchAll();
foreach ($result as $row)
{
$id = $row['id'];
$my_array[$id] = $row;
}
return $my_array;
}
I would make the connection to the database $dbh once outside this function.
My function:
function sql_query($s, $x) {
$query = mysql_query($s);
global $mysql;
while($mysql = mysql_fetch_array($query)) {
return;
}
}
Now it's work only with $mysql variable:
echo $mysql['username'];
How to make it works only with:
sql_query("select * from users where id = '1' limit 1", "varname");
$varname['username'];
I want to set a SQL Query and Variable name in function, like:
sql_query("sqlquery", "variable");
echo $variable['id'];
Thanks for reply!
function sql_query($s, &$x) {
global $mysql;
$query = mysql_query($s);
$result = mysql_fetch_array($query);
foreach($result as $key => $value) {
$x[$key] = $value;
}
}
This should assign each variable that is returned by the query to a key in array $x (assuming it is an array). Notice that I am passing $x by reference instead of by value, eliminating the need to return anything.
To give some context, a little while ago with the help from VolkerK on this very site I created a function that queries an Oracle database and places the content into a neatly formatted PHP array, depending on the index. Here's the original question.
The problem is, in some cases I just want to return a single value from a quick query, and when I do I get the the following error: Notice: Undefined index:
Here's the code I'm using:
function oracleGetData($query, $id = null) {
global $conn;
$results = array();
$sql = OCI_Parse($conn, $query);
OCI_Execute($sql);
while ( false!==($row=oci_fetch_assoc($sql)) ) {
$results[ $row[$id] ] = $row;
}
// remove one layer if there's only one record
if(count($results) == 1 and is_null($id)) {
$results = array_pop($results);
}
return $results;
}
I have tried changing the line that populates the array like so:
if(is_null($id)) {
while ( false!==($row=oci_fetch_assoc($sql)) ) {
$results[ $row ] = $row;
}
} else {
while ( false!==($row=oci_fetch_assoc($sql)) ) {
$results[ $row[$id] ] = $row;
}
}
Basically if the $id variable is null, remove all references to it, but then I get a 'Warning: Illegal offset type' error.
Any help would be much appreciated, I've tried passing in the single field I require into the function but get the same error.
Thank you
Perhaps if $id is NULL you could just use sequential numbers for the indexes, as in:
function oracleGetData($query, $id = null)
{
global $conn;
$results = array();
$sql = OCI_Parse($conn, $query);
OCI_Execute($sql);
if(is_null($id)) {
$idx = 1;
while (false!==($row=oci_fetch_assoc($sql))) {
$results[ $idx ] = $row;
$idx = $idx + 1;
}
} else {
while ( false!==($row=oci_fetch_assoc($sql))) {
$results[ $row[$id] ] = $row;
}
}
// remove one layer if there's only one record
if(count($results) == 1 and is_null($id)) {
$results = array_pop($results);
}
return $results;
}
Share and enjoy.
Have just come across a problem where I believe this is the solution.
At the moment I have the following code:
function siteUsers()
{
global $database;
$q = "SELECT username, id FROM ".TBL_USERS."";
return mysql_query($q, $this->connection);
}
function generateUserArray()
{
$u = array();
$i = array();
$result = $this->siteUsers();
while( $row=mysql_fetch_assoc($result))
{
$u[] = $row['username'];
$i[] = $row['id'];
}
return $u, $i;
}
As you can see, when I then go onto use foreach, the u and i get split apart.
Is there anyway that I could keep them together?
foreach ($u as $username) {
echo"<option value='$i'>$username</option>";
}
What I need it the option value to be the id and the visual value to be the username.
Is this possible?
Thanks
Use an associative array linking the ID to the username. I'm assuming here the IDs are unique.
$users = array();
while( $row=mysql_fetch_assoc($result))
{
$users[$row['id']] = $row['username'];
}
return $users;
Then:
foreach ($users as $id => $username)
{
echo "<option value='$id'>$username</option>";
}
foreach($u as $idx => $username)
{
echo"<option value='".$i[$idx]."'>$username</option>";
}
assuming equal length and that php function can return two values :\