Pass mysql_query results to foreach - php

I used the following code to to get list of users facebook friends and ccheck it against users in an app database. This code would return the users of the app, who are Facebook friends of the user.
$friends_set = '(';
foreach($friends["data"] as $value) {
$friends_set .= $value['id'].',';
}
$new_set = preg_replace('/,$/',')',$friends_set);
$res = mysql_query("SELECT * from user AS u, upload AS up WHERE u.fb_id IN $new_set AND u.fb_id=up.user_id") or die(mysql_error());
while($row = mysql_fetch_array($res)) {
echo $row['fb_id']. "". $row['first_name'];
echo "<br>";
}
$data['top_friends']=$res;
$this->load->view('myview');
This code works. It is in a controller of my codeigniter application and it successfully echos the correct data onto the page.
However now I need to print the result of the query in a for each statement in my view like this:
<?php foreach ($top_friends as $me) : ?>
<div >
<p><?php echo $me['first_name']; ?></p>
<?php endforeach; ?>
However when I try getting the query results in the view using the for each it doesn't work.
How do i fix this?

You could try it the codeignitor way, Create a model function say get_top_friends and i assume that you are passing a comma separated string as argument like $fb_id = '45,65,78,89'. Say facebook_model is the name of the model then :
class Facebook_model extends CI_Model{
//other functions and constrcutor here
//function to get the top friends
function get_top_friends($fb_id){
$fbId = explode(",",$fb_id)
$this->db->select('*');
$this->db->where_in('fb_id',$fbId);
$this->db->order_by('points','desc');
$this->db->limit(10);
$query = $this->db->get('user');
if ($query->num_rows() < 1) return FALSE;
return $query->result_array();
}
}
And make change in your code as below:
$friends_set = '';
foreach($friends["data"] as $value) {
$friends_set .= $value['id'].',';
}
$new_set = preg_replace('/,$/',')',$friends_set);
$res = $this->facebook_model->get_top_friends($new_set);
$data['top_friends']=$res;
$this->load->view('myview',$data);
And now in view you can try
foreach ($top_friends as $me){
echo $me['first_name'];
}
[Updated for user ]
If you want to do it as in your question : then try,
$result = array();
while($row = mysql_fetch_array($res)) {
$result[] = $row;
}
$data['top_friends']=$result;
$this->load->view('myview',$data);//pass data to view

Related

Implement If condition in PHP array

I am new to PHP function. I think following problem can be solved using function. Here I am able to store html form data in database which is passed from ajax using following code. But I am little bit confused where to implement if condition. If Data has been submitted, I want to stop data replication.
My working php code
if(isset($_POST["section_name"])){
$section_name = $_POST["section_name"];
$class_id = $_POST["class_id"];
for($count = 0; $count<count($section_name); $count++)
{
$query =$con->prepare('INSERT INTO section(class_id, section_name) VALUES (:class_id, :section_name)');
$query->bindParam(':class_id', $class_id);
$query->bindParam(':section_name', $section_name[$count]);
$query->execute();
echo "Section has been assigned";
}
}
Now, I want to include above code in following else condition.
$query =$con->query('SELECT * FROM section');
while($row=$query->fetch(PDO::FETCH_ASSOC)){
if(($_POST["class_id"]==$row["class_id"])&&($_POST["section_name"]==$row["section_name"])){
echo "Section has already assigned in this class ";
}
else{
// insert...
}
}
When I try to merge code, I can't handle. Please help me
You have pretty much everything, you just need to wrap it in a function like this:
function insert() {
if(isset($_POST["section_name"])){
$section_name = $_POST["section_name"];
$class_id = $_POST["class_id"];
for($count = 0; $count<count($section_name); $count++)
{
$query =$con->prepare('INSERT INTO section(class_id, section_name) VALUES (:class_id, :section_name)');
$query->bindParam(':class_id', $class_id);
$query->bindParam(':section_name', $section_name[$count]);
$query->execute();
echo "Section has been assigned";
}
}
}
And then you call it like this:
$query =$con->query('SELECT * FROM section');
while($row=$query->fetch(PDO::FETCH_ASSOC)){
if(($_POST["class_id"]==$row["class_id"])&&($_POST["section_name"]==$row["section_name"])){
echo "Section has already assigned in this class ";
}
else{
insert();
}
}

How to display SQL result separately

I'm currently making a webpage which is meant to show all it's content from the database. So I made an SQL command which selects the data needed for only 1 particular field on the webpage.
Is it possible to make the SQL command so that it get's all the content for the page at once and that ill still be able to display it separately?
If so, how? Thanks
function dbGet() {
global $conn;
global $return;
$sql = SELECT * FROM testTable;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$return = $row["text"];
return $return;
}
}
else {
echo "0 results";
}
// $conn->close();
}
You can use in this way through which you can identify records has been there or not.
function dbGet() {
global $conn;
// I am not sure what is the datatype of $return here.
// if it's having a predefined format,
// please push the records into $return instead of creating as an array,
// which will be taken care by framework if any you are using.
// global $return;
$return = array('status' => false, records => []);
$sql = "SELECT text FROM testTable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$return['status'] = true;
while($row = $result->fetch_assoc()) {
$return['records'][] = $row["text"];
}
}
// $conn->close();
return json_encode($return);
}
Just echo the results inside while loop instead of returning in whatever format you wish
If you are using php, you can try something like
echo $row["text"];
Hope it helps
Let me know if you require any further help
First you should fix your return code as #AbraCadaver mentioned :
$return[] = $row["text"];
Then you can use foreach in your html :
<?php
foreach($return as $r){
echo $r['text'];
}
?>
I think a Json encoding : json_encode will work well.
Try this: http://php.net/manual/pt_BR/function.json-encode.php

How to decode json data from post method for android app in php?

I am developing an app, in which I pass the credentials and then pass it through post method. In this page, I want to access the regno and pass value that were filled in the login page. But I am not getting the values. I tried echoing the values as $data->regno, but I got Null value. Please tell me what am I doing wrong.
<?php
ini_set('display_errors', '0');
error_reporting(0);
require_once("include/db.php");
class mysendclass{
public $name="Invalid";
public $priority=-1;
public $url="";
}
class myrecclass{
public $regno="";
public $pass="";
}
$e=new mysendclass();
$g=new myrecclass();
if(isset($_POST))
{
$data=json_decode(file_get_contents('php://input'));
foreach ($data AS $key => $value) $g->{$key} = $value;
$query = "SELECT priority, name, url FROM users WHERE regno='{$data->regno}' AND pass='{$data->pass}' LIMIT 1";
echo ($query);
$res = mysql_query($query, $conn) or die(mysql_error());
$found = mysql_fetch_array($res);
echo ($found);
if($found)
{
$e->name=$found['name'];
$e->priority=$found['priority'];
$e->url=$found['url'];//url
}
echo json_encode($e);
}
?>
When I post the credentials, I receive this, inspite of posting correct credentials from the database:
{"name":"Invalid","priority":-1,"url":""}
use this..
<?php
$abc = array();
$abc['my_first_name'] = "Suresh";
$abc['my_last_name'] = "Kumar";
echo json_encode($abc);
?>
return valid json sting is
{"my_first_name":"Suresh","my_last_name":"Kumar"}
This is a simple example for your understanding..
In your query you encode a object not a array i am not sure but i think this is your prob
please try this...
<?php
ini_set('display_errors', '0');
error_reporting(0);
require_once("include/db.php");
class mysendclass{
public $name="Invalid";
public $priority=-1;
public $url="";
}
class myrecclass{
public $regno="";
public $pass="";
}
$records = array();
$e=new mysendclass();
$g=new myrecclass();
if(isset($_POST))
{
$data=json_decode(file_get_contents('php://input'));
foreach ($data AS $key => $value) $g->{$key} = $value;
$query = "SELECT priority, name, url FROM users WHERE regno='{$data->regno}' AND pass='{$data->pass}' LIMIT 1";
echo ($query);
$res = mysql_query($query, $conn) or die(mysql_error());
$found = mysql_fetch_array($res);
echo ($found);
if($found)
{
$records['name']=$found['name'];
$records['priority']=$found['priority'];
$records['url']=$found['url'];//url
}
echo json_encode($records);
}
?>
Use array as parameter in json_encode() function instead of object.

how to query two tables from database and show the result in a single row using codeigniter

I have two tables One for users and the other for project listing
My problem is that i want to display each project(from project_table)and email belonging to user who listed the project(from user_table) on a single row
The project_table has a row for user_id(i.e id from user_table that identifies the user who posted the project)
here's my view(project_view):
I this case im displaying data from project_table but i want to display email for a particular user from user_table
<?php
foreach($query as $row)
{
?>
<p> <?echo $row->pro_name ?></p>
<p> <?echo $row->duration ?></p>
<p> <?echo $row->budget ?></p>
<p>User email will be displayed here</p>
<?
}
my model:
function get_projects()
{
$query = $this->db->get('project_table');
return $query->result();
}
my controller:
function show_projects()
{
$data['query']=$this->project_model->get_projects();
$this->load->view('project_view', $data);
}
Any ideas on how to implement this will be much appreciated
You can use joined query in your model
function get_projects()
{
$query =$this->db->select('p.*,u.email')
->from('project_table p')
->join('user_table u','p.user_id = u.id')
->get();
return $query->result();
}
And in your view you can do so
<?php
foreach($query as $row)
{
?>
<p> <?php echo $row->pro_name; ?></p>
<p> <?php echo $row->duration; ?></p>
<p> <?php echo $row->budget; ?></p>
<p><?php echo $row->email;?></p>
<?php
}
?>
I would rewrite controller and model function to allow for a user parameter:
function get_projects($user=null)
{
if ($user == null){
$query = $this->db->get('project_table');
}else{
$query = $this>db->get('project_table')->where('user_id',$user);
}
return $query->result();
}
function show_projects($user)
{
$data['query']=$this->project_model->get_projects($user);
$this->load->view('project_view', $data);
}
Now you can call your controller with a user parameter
http://..../show_user/1
1st approach is JOINs
$this->db->select('project_table.* as project, user.id as user_id, user.email as email')
->from('project_table')
->join('user', 'project.id = user_id');
$result = $this->db->get();
2nd not recommended
function get_projects()
{
$query = $this->db->get('project_table');
return ($query->num_rows() > 0) ? $query->result() : FALSE;
}
function get_email($id = FALSE) {
if ($id === FALSE) return FALSE;
$query = $this->db->get_where('user', array('user_id' => $id));
return ($query->num_rows() > 0) ? $query->result() : FALSE;
}
somewhere in controller...
if (!$projects = $this->model->get_projects()) {
foreach ($projects as $key => $project) {
# code...
$projects[$key]->user_email = $this->model->get_email($project->user_id);
}
//projects is now with user_email field
$this->load->view()...
} else {
//no data recieved
redirect(); //redirect to default_controller
}
Try join this -
1) Model
function get_projects()
{
$this->db->select('*');
$this->db->from('project_table');
$this->db->join('user_table', 'project_table.user_id = user_table.id');
$query = $this->db->get();
if($query->num_rows() > 0)
{
return $query->result();
}
}
2) Controller
$data['user_project'] = $this->project_model->get_projects();
$this->load->view($view, $data);
3) View
foreach($user_project as $row)
{
echo "<p>" .$row->pro_name. "</p>";
echo "<p>" .$row->duration. "</p>";
echo "<p>" .$row->budget. "</p>";
echo "<p>" .$row->email. "</p>";
}

How to display more number of array results in a single array?

I have two tables: loginandfollow`.
Table name: login
Fields: id,email,username,imageurl
Table name: follow
Fields: id:user_id:follow_id
It's like a Twitter follower's concept. I want to get the details of myfollower name and also myfollower's following person's name.
For that I have written the coding as like below.
public function follw ()
{
if( $this->input->get("userid") )
{
extract($this->input->get());
$followers_list = array();
$follower = array();
$query = $this->db->query('select follow_id from follow where user_id = '.$userid.'')->result();
foreach($query as $row)
{
$follower['follower_id'] = $row->follow_id;
if($follower['follower_id'] == "")
{
echo "hi";
}
else
{
$query3 = $this->db->query('select username from login where id = '.$follower['follower_id'].'')->result();
foreach($query3 as $row3)
{
$follower['followuser'] = $row3->username;
}
$query1 = $this->db->query('select follow_id from follow where user_id = '.$follower['follower_id'].'')->result();
foreach($query1 as $row1)
{
$follower['follow_id'] = $row1->follow_id;
if($follower['follow_id'] == "")
{
echo "jeeva";
}
else
{
$query2 = $this->db->query('select username from login where id = '.$follower['follow_id'].'')->result();
foreach($query2 as $row2)
{
$follower['username'] = $row2->username;
}
}//second for each in else loop
}//first foreach in else loop
}//main else
$followers_list[] = $follower;
}
$str = json_encode($followers_list);
echo stripslashes($str);
}
else
{
echo '[{"status":"Failure - Error Occured - Not Enough Details provided"}]';
}
}
I get the output like this:
[{"follower_id":"12","followuser":"janmejoy","follow_id":"24","username":"sarvana"},{"follower_id":"10","followuser":"jeeva","follow_id":"23","username":"selva"},{"follower_id":"6","followuser":"raj","follow_id":"17","username":"jeeva"},{"follower_id":"23","followuser":"selva","follow_id":"22","username":"guru"}]
This output displays myfollower's name and myfollower's following person name, but the problem is it displays only one member of myfollower's following person name.
However, I want to the output like this:
[{"follower_id":"12","followuser":"janmejoy",{"follow_id":"24","username":"sarvana",follow_id":"13","username":"jai",follow_id":"9","username":"raj"}},{"follower_id":"10","followuser":"jeeva","follow_id":"23","username":"selva"},{"follower_id":"6","followuser":"raj","follow_id":"17","username":"jeeva"},{"follower_id":"23","followuser":"selva","follow_id":"22","username":"guru"}]
[{"follower_id":"12","followuser":"janmejoy",{"follow_id":"24","username":"sarvana",follow_id":"13","username":"jai",follow_id":"9","username":"raj"}},{"follower_id":"10","followuser":"jeeva","follow_id":"23","username":"selva"},{"follower_id":"6","followuser":"raj","follow_id":"17","username":"jeeva"},{"follower_id":"23","followuser":"selva","follow_id":"22","username":"guru"}]
This code is invalid JSON variable. i can't solve this question for you. Please update your question.

Categories