echo result from function from table in database - php

so i am learning to write functions. Now i know how to echo stuff into a foreach but i do not know how to print a single row outside a foreach (like i only have 1 row in my table and want to print the id and username out of it) how do i do this?
my function :
public function gegevens(){
$stmt = $this->conn->prepare("SELECT * FROM gegevens_locatie");
$stmt->execute();
$result = $stmt->fetchAll();
//Return result
return $result;
}
when i call that function on my other page i call it with :
require_once 'class/class.overig.php';
$overig = new OVERIG();
i have tried stuff like print_r($overig->gevens()) and with a echo but i cant seem to make it work. So how can i do this?

Because you are using ->fetchAll() you will always get an array of rows even if there is only one row returned. You also need to use the correct method name on your call.
So all you need to do is
$arr = $overig->gegevens();
if ( count($arr) == 1 ) {
echo $arr[0]['id'];
echo $arr[0]['username'];
}
if ( count($arr) > 1 ) {
foreach ( $arr as $row) {
echo $row['id'];
echo $row['username'];
}
}

"I have tried stuff like print_r($overig->gevens()) and with a echo but i cant seem to make it work. So how can i do this?"
The Name of the Method you called does NOT match the Name of the Method in your Class. In your Class, You have: gegevens() but in your Call: you specified: gevens(). Unless this is just a normal Typo; you should start your Debugging from there.
In other words; your Call should have been: print_r($overig->gegevens()).
THE CLASS:
<?php
class OVERIG{
public function gegevens(){
$stmt = $this->conn->prepare("SELECT * FROM gegevens_locatie");
$stmt->execute();
$result = $stmt->fetchAll();
//Return result
return $result;
}
}
USING THE CLASS:
<?php
require_once 'class/class.overig.php';
$overig = new OVERIG();
$result = $overig->gegevens();
// TRY DUMPING THE VARIABLE: $result:
var_dump($result);
// TO ECHO OUT SOME VALUES:
if($result){
foreach($result as $key=>$item){
if(is_string($item)){
echo $item;
}
}
}

Related

Why is the array is always empty at this point despite the fact that I added data there?

$result = mysqli_query($con, "SELECT * FROM users");
$usersArray=[];
tableArrayPushData($result, $usersArray);
function tableArrayPushData($result, $tableArray){
while ($row = $result->fetch_assoc()) {
$str = '';
foreach ($row as $value) {
$str = $str.$value.'|';
}
$newStr = rtrim($str, "| ");
array_push($tableArray,$newStr);
}
}
for ($i=0; $i<count($usersArray); $i++){//array is always empty at this point
echo "Ok";
echo "<br>";
}
I don't understand why, but usersArray is empty despite the fact that I added data there.
The MySQL table has rows with data, so it can't be empty.
You should use the & operator to allow the function to access the outer variable, like this:
function tableArrayPushData($result, &$tableArray) {}
Or use return.

CodeIgniter - return paramater as row

This is my code as of now which returns Hassum Harrod profile as JSON which is perfect. What I need to happen is for my parameter to be passed into the query string instead of having a name so that when the url is passed a name the query returns that person's profile from the DB. When I change the name Hassum Harrod to the variable $name I get the following error:
Unknown column 'Hassum' in 'where clause'
SELECT name, short_name, reknown, bio FROM profile WHERE name = Hassum%20Harrod
This is my code as now:
Controller
public function getPerson($name) {
// loads the DBModel.php
$this->load->model('DBModel');
$query = $this->db->query("SELECT name, short_name, reknown, bio FROM profile WHERE name = 'Hassum Harrod'");
$data['profile'] = $query->row();
$this->load->view('profileView', $data);
}
View
echo json_encode($profile);
Please Read : http://www.codeigniter.com/user_guide/general/models.html
http://www.codeigniter.com/user_guide/database/query_builder.html
Try this way
Add this method to your model it should be like this
// in your model
public function getNames($name) {
$data = array();
$this->db->select(*);
$this->db->like('name', $name);
$query = $this->get('profile');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$data[] = $row;
}
}
return $data;
}
Your Controller should be like this
public function getPerson($name) {
$this->load->model('DBModel');
$data = $this->DBModel->getNames($name);
// you can encode in json here
$data['profile'] = json_encode($data);
$this->load->view('profileView', $data);
}
http://www.codeigniter.com/user_guide/general/controllers.html
In view :
echo $profile;
You are using LIKE keyword in your query so we could assume there would be more than one result in return from DB. In that case you would need $query->result() instead. Secondly, even if there is just one returned row, this code:
$data['profile'] = $query->row() > 0;// assigning variable to condition (TRUE|FALSE)
will return boolean value, but not result itself.
This is simplified code for that and you can check:
<?php
$a = ['a', 'b', 'c'];
var_dump($b = $a > 0);// TRUE
Feel free to start using basic examples from docs. It will help you maintaning code:
$query = $this->db->query("YOUR QUERY");
$row = $query->row();
if (isset($row))
{
echo $row->title;
echo $row->name;
echo $row->body;
}
Again, if you expect only one possible row from DB, you can try with this code. But if you are not certain if there would be several possible rows, you have to use code for retreiving that:
$query = $this->db->query("YOUR QUERY");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
When you set this all working than you can work on converting object or array to JSON string.
It would follow syntax:
$json = json_encode($row);
If multiple rows is returned, it would be most easier to return result_array() or row_array() from DB since arrays are easily converted ti JSON, although there are suitable solutions.
After all, model that is loaded at the beginning of method is not used at all.
Docs.

how to iterate arraylist in php

What my code does:
I am returning arraylist from a php method -->method name:- getSubjectInfo().
And in my (Index.php) page i am getting this arraylist values in a $results variable. Here i am stuck how to iterate the arraylist values in the index.php page?.
My Problem: How to iterate the arraylist ($results) in my index.php page? Please see my below mention code
i have used $results = $sub_info->fetchAll(PDO::FETCH_OBJ); in my method for generating list.
index.php
<?php
include_once '../../classes/conn/connection.php';
include_once '../../classes/setups/Subdetails_setup.php';
$con = new connection();
$info = new Subdetails_setup($con);
$results = $info->getSubjectInfo();
echo $results; //this is returning a list of objects. My problem is how can i iterate these values
?>
and i tried like this echo (each($results)); but this is printing my values in a single line
like this:- Subject Name 1 FIction1Non FIction2
& My Subdetails_setup.php Class is having method getSubjectInfo() :-
function getSubjectInfo()
{
$sub_info = $this->con->prepare("SELECT * FROM subjectdetails");
$sub_info->execute();
$results = $sub_info->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $key)
{
echo $key->subject_name;
echo $key->subject_id;
}
// Return the result array
return $results;
}
Please help me for this.
-Ashutosh
This code in your Subdetails_setup.php needs to be removed, and put on the index.php. You don't need it in subdetails, just return the result.
foreach ($results as $key)
{
echo $key->subject_name;
echo $key->subject_id;
}
If you want to check if it's all working, change your index.php and add this line:
$results = $info->getSubjectInfo();
var_dump($results);
Now that var_dump() works, replace the line with the earlier code, modified to show a table:
foreach ($results as $key)
{
echo "<tr>";
echo "<td>".$key->subject_name."</td>";
echo "<td>"$key->subject_id."</td>";
echo "</tr>";
}

php function in a while Loop

i searched all over the web or i just don't see it.
I want to do the following:
<?php
function abc(){
$sql = "SELECT * FROM table";
$result = mysql_fetch_assoc($sql);
$data = mysql_fetch_assoc($result);
}
?>
<? while(abc()) : ?>
<?=article_title()?>
<?=article_content()?>
<?=endwhile;?>
Could somebody give me a direction and/or example?
Thank you very much
PHP does not have generator/iterator functions, so you cannot do that.
You can however return an array and iterate over that array:
function abc() {
// ...
$rows = array();
while($row = mysql_fetch_assoc($result)) { $rows[] = $row; }
return $rows;
}
foreach(abc() as $row) {
// do something
}
If the functions you call need access to the row, pass it as an argument. Using global variables for it would be very bad/nasty
have you tried to do something like that?
<?php
function getData(){
//get the data from the database
//return an array where each component is an element found
}
$elems = getData();
foreach($elems as $e){
doSomethingWith($e);
}

PHP while loop times

This is my first time try to use object oriented programming. I'm trying to repeat the timeslot from the database but I'm only getting one result.
timeslot table contains:
10:00:00
10:15:00
10:30:00
in PHP class:
class booking {
function __construct($mysqli) {
}
function get_timeslot() {
global $mysqli;
$q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
return $r['times'];
endwhile;
$mysqli->close();
}
}
in the webpage to showing the looping times:
$booking = new booking($mysqli);
<?php echo $booking->get_timeslot(); ?>
result:
10:00:00
return is returning the value for your function, thus you'll only receive 1 value returned. Try
echo $r['times'].'<br/>';
or
function get_timeslot(){
global $mysqli;
$q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");
$timeSlots = array();
while($r = $q->fetch_array(MYSQLI_ASSOC))
{
$timeSlots[] = $r['times'];
}
$mysqli->close();
return $timeSlots;
}
the return statement stops the while loop from continuing any further, and exits the function. You'll either need to modify the function to return an array of time slots, or modify your logic to expect only the first result from the database.
The return statement will exit the function immediately it's called. Instead return you should add the item to array than return the entire array:
class booking {
function __construct($mysqli){}
function get_timeslot(){
global $mysqli;
$q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
$res[] = $r['times'];
endwhile;
$mysqli->close();
return $res;
}
}
function get_timeslot() {
global $mysqli;
$q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
// Cast to array
$t[] = $r['times'];
endwhile;
$mysqli->close();
// Return Array
return $t;
}
// Calling the function
$booking = new booking($mysqli);
// Add print_r() as the return is now in an array format
echo "<pre>".print_r($booking->get_timeslot(),true)."</pre><br />\n";
Because you are using return $r['times']; inside the loop.
This should solve your problem:
function get_timeslot(){
global $mysqli;
$returnArray = array();
$q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
$returnArray[] = $r['times'];
endwhile;
$mysqli->close();
return $returnArray; // now that all results are fetched from DB, return array containing them
}
On other note, using global keyword inside a class method or anywhere for that matter i not advisable, since global scope enables any process to access and change global variable.
I would advise you to try using other means of accessing your DB object (object registry, protected property...)
Also using alternative syntax for while loop (while(): ... endwhile;) is not very readable, but one can debate about that.
Try this:
class booking {
function __construct($mysqli){}
function get_timeslot()
{
global $mysqli;
$q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");
$return = '';
while ($r = $q->fetch_array(MYSQLI_ASSOC)) :
$return.= $r['times'] . '<br/>';
endwhile;
$mysqli->close();
return $return;
}}

Categories