Retrieving more than one row of data using PHP - php

I'm trying to create a function that runs a query that returns all of the data located in my MySQL database.
My current code only returns the one row of data (there are 7)
function staff_get() {
$this->load->database();
$sql = 'SELECT * from Staff';
$query = $this->db->query($sql);
$data = $query->row();
$this->response($data, 200);
}
I'd imagine it has something to do with the line "$data = $query->row();" however I've tried switching "row" with "array" but this doesn't work. The text is designed to come out as plaintext so that I can manipulate it using a jQuery template.
Thank you for your help in advance.

You need to encase the results in a while loop. Something along the lines of this.
function staff_get() {
$this->load->database();
$sql = 'SELECT * from Staff';
$query = $this->db->query($sql);
while($data = $query->row()) {
$this->response($data, 200);
}
}

Related

Joining two tables in Codeigniter using PHP

I am trying to join two tables and return an array in my Model method in CodeIgniter with php. I've gone through a few previously posted similar questions on stackoverflow and modified my code accordingly. But they don't seem to work. Hence would love to know what's wrong with the following.
I'm using the following method but am currently getting exceptions. Would appreciate suggestions in this regard.
Model Method
public function getUserDetails($username)
{
$uid = $this->getUserUid($username);
$this->db->select('s.uid, s.name,s.phone, s.studentId, s.type, sp.profiledesc, sp.age');
$this->db->from('sysuser as s');
$this->db->join('studentprofile as sp', 's.uid = sp.uid', 'left');
$this->db->where(array('s.uid' => $uid));
$query = $this->db->get();
return $query->result();
}
Controller
$data1['details'] = $this->userModel->getUserDetails($username);
$this->load->view('studentDashboard/viewProfile',$data1);
View
...
<h2>
<?php foreach($details as $detail){?>
<?php echo $detail->s.name;?>
<?php }?>
</h2>
...
In the view, I've also tried just echoing $detail->name but this doesn't work either.
At first, use print_r($details) for checking your data. If it's returning anything or not.
Then echo your value like this $detail['name']
Fixed Code:
public function getUserDetails($username)
{
$uid = $this->getUserUid($username);
$this->db->select("*");
$this->db->from('sysuser');
$this->db->join('studentprofile', 'studentprofile.uid = sysuser.uid');
$this->db->where('sysuser.uid',$uid);
$query = $this->db->get();
return $query->result();
}
Look, i´m not sure that i understood your code, what means this line
$uid = $this->getUserUid($username);
You´re calling a method and sending the name to retrieve the userid, right?
I´ll write that method like you should have it:
public function getUserid($user){
$this->where->id($user);
return $this->get('whatever table')->row();
//i think you forgot this ->row()
}
then
public function getUserDetails($username)
{
$uid = $this->getUserUid($username);
//here already you should bring with ->row() already
//you can use this var_dump here to confirm too
//var_dump($uid);
//exit;
$this->db->select('s.uid, s.name,s.phone, s.studentId, s.type, sp.profiledesc, sp.age');
//line´s right
//the from method is disposable, so i put it into the get but here it´s right too
$this->db->join('studentprofile as sp', 's.uid = sp.uid', 'left'); //ok
$this->db->where($uid); //this line is the wronger, i´ve made the fix
//as this is an where, you´d bring only one value with ->row() from that other method
$query = $this->db->get('sysuser as s');
//the 'from' i putted here, just to write a line less
return $query->result();
when you need to test what you´re returng do a var_dump here
//commenting the return above
//$test = $query->result();
//var_dump($test);
}

Store fetched query into global array PHP

I'm trying to create a global variable which contains user specific data from my database. I've been looking over the internet but I couldn't find the right answer. I'm not quite sure how to approach this.
At this point of code, the user has been registered and logged in and his login data is saved inside $s_email and $s_password, which are session variables.
Here's some code (mysql.php) which contains the mysql class:
class mysql {
// Create database connection
private $db;
function __construct() {
$this->db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME) or
die('Database fout.');
}
// Receive user data based on cookie, then fetch this data into an array
function getUserData($s_email, $s_password, $data){
$sql = "SELECT
`id`,
`firstname`,
`lastname`,
`city`,
`country`,
`gender`,
`bio`,
`active`,
`member_since`
FROM `users`
WHERE email = '$s_email'
AND password ='$s_password'";
// perform the query and store the result
$result = $this->db->query($sql);
// if the $result contains at least one row
if ($result->num_rows > 0) {
// output data of each row from $result
$data = array();
global $data;
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
}
}
And this is my profile.php which will try to run the function (the echo $data[''] does not work, but that's the kind of approach I would like to take on this system):
<?php
// Receive user data and send it to mysql class
$mysql->getUserData($s_email, $s_password, $data);
echo $data['email'];
?>
Eventually I'm trying to create a simple access method to the array variables.
NOTE: I've only been scripting PHP and MySQL for 2 days, so any advice on my code is really appreciated.
Thank you,
Don't use globals.
In your function (don't use $data as an argument):
function getUserData($s_email, $s_password) {
// code
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;
}
Then to use it (don't pass $data as an argument):
$data = $mysql->getUserData($s_email, $s_password);
Now you have rows so loop over them:
foreach($data as $row) {
echo $row['email'];
}
And you need to select email in the query.
I will first tell you how to do it and right after will explain why you shouldnt be doing that.
How to do it
To let the getUserData method to alter the value of the $data variable you are giving as argument you need to pass it by reference, like this:
function getUserData($s_email, $s_password, &$data) {
Why you should not be doing this in this situation
Keeping things brief. Because there are by far better approaches (like the one AbraCadaver is suggesting) and you dont really need to pass the $data by reference in the first place.

Array to string conversion error?

I am using PDO and trying to display how many users are in a table, however I get this error:
Notice: Array to string conversion in C:\Users\admin.phtml on line 10 Array
Then in my Admin class:
public function CountUsers()
{
$query = "SELECT * FROM Users";
$statement = $this->_dbHandle->prepare($query);
// Then execute the query
$statement->execute();
// This will return the row from the database as an array
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
Then in my Admin Controller I have:
$Admin = new Admin();
$CountUsers = $Admin->CountUsers();
To display the results I have this in my phtml:
<var><?php echo $CountUsers; ?></var>
Does anyone understand what I am doing wrong?
You should try to count the users in query, like so:
public function CountUsers() {
$query = "SELECT COUNT(1) FROM Users";
$statement = $this->_dbHandle->prepare($query);
if($statement->execute()) {
// This will return COUNT(1) field
return $statement->fetch(PDO::FETCH_NUM)[0];
}else{
return 0; // should the query fail, return 0
}
}
If you want to stick to counting in PHP (which you shouldn't), modify your code to do:
return count($statement->fetchAll(PDO::FETCH_ASSOC));
But you shouldn't query all of the data just to count and discard it. Using SQL's count is far more performant for several reasons:
You don't fetch the actual data. If your data set is big, you have to transfer megabytes or gigabytes over sockets. Which is not too good idea, even if the database is on the same machine.
You don't store the data in PHP. When using fetchAll, it will store all of the data into PHP array, taking up memory
MySQL engine might use optimisations which further speed things up (looking up the record count directly)
To display a meaningful text, or do something with this function you can:
function CheckUsers() {
$userCount = CountUsers();
if($userCount == 0) {
echo 'No users found';
}else{
echo $userCount . ' users found';
}
}

Generic MySQL Select All Function

I write a lot of SELECT * FROM... kind of queries in my web sites. I'd like to write a function that looks after this for me so I can call on it more quickly, without using more advanced techniques like PDO and OOP. Im just confused on how I would call the data I retrieve from the database, particularly when looping through the array's results.
I'd love something like this:
function selectAll($tableName, $limitAmount) {
global $dbConnection;
$query = mysql_query("SELECT * FROM $tableName ORDER BY id LIMIT $limitAmount");
$row_result = mysql_fetch_assoc($query);
return $row_result;
}
Say it was a bunch of news posts. Id like to loop through the results in one of the typical ways:
// CALL THE FUNCTION
selectAll('news_table', '10');
// SOMEHOW LOOP THROUGH RESULTS??
do {
echo "<h2>".$row_result['title']."</h2>";
} while ($row_result = mysql_fetch_assoc($query));
Obviously this isn't how I loop through the bespoke results of a function. Im not even sure if my function is correct.
Any help is greatly appreciated.
EDIT: Forgot to return a result inside the function and call the actual function. My bad. Updated now.
There is no point in having such a function called like yours.
Just make it like this
function fetchAll($query) {
$res = mysql_query($query) or trigger_error("db: ".mysql_error()." in ".$query);
$a = array();
if ($res) {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
and use it with whatever query:
$data = fetchAll("SELECT * FROM news_table ORDER BY id LIMIT 10");
foreach ($data as $row) {
echo $row['title'];
}
An SQL query being a powerful program itself. Do not reduce it's power to silly selects.
Use SQL to represent data processing logic and this helper function to avoid repetitions.

PHP Variable - Multiply pages

I have a functions.php page, I have included in ALL my other php pages. What I want is a function in my functions.php page, I can use in all the other pages.
I have tried this:
function getSetting()
{
$r=mysql_query("SELECT * FROM settings");
if(mysql_num_rows($r) == 0)
return false;
else
$sdata=mysql_fetch_assoc($r);
return $sdata;
}
The thing I want to, I want to get the data from the row next to the name in the following picture: http://awesomescreenshot.com/0bci8x472
Example:
If I write $sdata['sitename'], I want it to output "ptcify"
Thanks!
Try using mysql_fetch_array() with MYSQL_ASSOC as documented at this link http://www.php.net/manual/en/function.mysql-fetch-array.php.
There are a lot of things you could do to further improve your code implementation i.e OOP, using better database abstraction libraries(even switching to PDO insted of PHP_MYSQL is an improvement), but this should work straight of the bat.
Most questions usually have a ? in them somewhere, to indicate an actual question. I'm not sure what the problem with your code is, but I'm guessing you're only getting a single "setting" result - if that query returns multiple rows, you have to loop over the result set and get each row, THEN return:
$r = mysql_query(...) or die(mysql_error());
$sdata = array()
while ($row = mysql_fetch_assoc($r)) {
$sdata[] = $row;
}
return $sdata
edit
$sql = "SELECT setting_name, setting_value FROM settings"
$result = mysql_query($sql) or die(mysql_error());
$sdata = array();
while($row = mysql_fetch_assoc($result)) {
$sdata[$row['setting_name']] = $row['setting_value'];
}
return $sdata;

Categories