PHP Change Function Query to be Direct Query Without Call The Function - php

I have an PHP code function get_news().
get_news function
function get_news(){
if($result = $this->db->query('SELECT * FROM tb_post WHERE post_id<>1 ORDER BY post_date DESC LIMIT 50')){
$return = '';
while($r = $result->fetch_object()){
$return .= '<p>id: '.$r->post_id.' | '.htmlspecialchars($r->post).'</p>';
}
return $return;
}
}
Now, I have 1 php file for fetching the data
if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
//the counters are diffrent so get new message list
$data['news'] = '';
$data['news'] .= $db->get_news();
$data['update'] = true;
}
My question is, how can I change the $db->get_news(); to be a direct query without call the function?

Try this
$news = '';
if($result = $this->db->query('SELECT * FROM tb_post WHERE post_id<>1 ORDER BY post_date DESC LIMIT 50')){
$return = '';
while($r = $result->fetch_object()){
$news .= '<p>id: '.$r->post_id.' | '.htmlspecialchars($r->post).'</p>';
}
}
$data['news'] = $news;
$data['update'] = true;

Related

join 2 table in one function

i want to join the data of 2 tables in 1 table and display the data of 2 tables. I already have function that load the one table. can someone modify this function code to get the 2 tables ? im just a beginner in php.
Model_users.php
public function getUserGroup($userId = null)
{
if($userId) {
$sql = "SELECT * FROM user_group WHERE user_id = ?";
$query = $this->db->query($sql, array($userId));
$result = $query->row_array();
$group_id = $result['group_id'];
$g_sql = "SELECT * FROM groups WHERE id = ?";
$g_query = $this->db->query($g_sql, array($group_id));
$q_result = $g_query->row_array();
return $q_result;
}
}
Controller User.php
public function index()
{
if(!in_array('viewUser', $this->permission)) {
redirect('dashboard', 'refresh');
}
$user_data = $this->model_users->getUserData();
$result = array();
foreach ($user_data as $k => $v) {
$result[$k]['user_info'] = $v;
$group = $this->model_users->getUserGroup($v['id']);
$result[$k]['user_group'] = $group;
}
$this->data['user_data'] = $result;
$this->render_template('users/index', $this->data);
}
Here you go
$this->db->select("ug.*,g.*");
$this->db->from("user_group ug");
$this->db->join('groups g', 'ug.user_id = g.group_id');
$this->db->where("ug.user_id",1);
$query = $this->db->get();
if ($query->num_rows() > 0) {
$result = $query->result();
} else {
$result = null;
}
return $result;

php with framework of codeigniter

function invitation_result()
{
$this->load->database();
$user_id = $_GET['user_id'];
$qry = mysql_query("select * from sent_invitations where user_id='$user_id'");
if (mysql_num_rows($qry) > 0)
{
while ($row = mysql_fetch_array($qry))
{
$mobile_number = $row['mobile_number'];
$qry1 = mysql_query("select mobile_number from users where mobile_number = '$mobile_number'");
$row1 = mysql_fetch_array($qry1);
$mobile_number = $row1['mobile_number'];
$users[] = array('mobile_number' => $mobile_number );
return $users;
}
}
}
The above is my coding.
In sent_invitation table there are 3 rows with user_id=11.
from there i m trying to get mobile_number of all three rows based on user_id.
the mobile_number of all 3 rows is different.
after geting mobile_number from sent_notification table.
i m comparing the mobile_number with mobile_number of users table.
i m seeing that 3 of them mobile_numbers are there in users table.
i m trying to show all of them.
bt problem is that my code id showing only one row and that is of last mobile number from 3
Since you are using Codeigniter You should follow the MVC pattern :
So the code in the controller should be :
public function invitation_result(){
$userId = 0;
if(($_GET['user_id']) && is_numeric($_GET['user_id']) && $_GET['user_id'] > 0){
$userId = $_GET['user_id'];
}
$data = $this->User_model->getDataFromID($userId);
return $data;
}
And the code for Model should be :
public function getDataFromID($userId){
$arrReturn = array();
if(($userId) && is_numeric($userId) && $userId > 0){
$this->db->select('*');//You can put the required fields here like : name,mobile_number...
$this->db->from('sent_invitations');
$this->db->where("user_id",$user_id);
$query = $this->db->get();
$result = $query->result_array();
if(!empty($result)){
foreach($result as $key=>$value){
$this->db->select('*');
$this->db->from('mobile_number');
$this->db->where("mobile_number",$value['mobile_number']);
$querySub = $this->db->get();
$resultSub = $querySub->result_array();
if(!empty($resultSub)){
array_push($arrReturn,$resultSub);
}
}
return $arrReturn;
}
}else{
return $arrReturn;
}
}
By the time I have written the Answer you would have solved the error ,but this answer will help future Users.
You should use while loop where you are getting mobile_number in inner loop.
function invitation_result()
{
$this->load->database();
$user_id = $_GET['user_id'];
$qry = $this->db->query("select * from sent_invitations where user_id='$user_id'");
if ($qry->num_rows() > 0)
{
while ($qry->result_array() as $row)
{
$mobile_number = $row['mobile_number'];
$qry1 = $this->db->query("select mobile_number from users where mobile_number = '$mobile_number'");
if($qry1->num_rows() > 0){
while($qry1->result_array() as $row1){
$mobile_number = $row1['mobile_number'];
$users[] = array('mobile_number' => $mobile_number );
}
return $users;
}
}
}
}
You should use codeigniter database query instead of mysql custom query. because mysql is deprecated. You can use below code:
function invitation_result()
{
$this->load->database();
$user_id = $_GET['user_id'];
$qry = mysqli_query("select * from sent_invitations where user_id='$user_id'");
if (mysql_num_rows($qry) > 0)
{
while ($row = mysql_fetch_array($qry))
{
$mobile_number = $row['mobile_number'];
$qry1 = mysql_query("select mobile_number from users where mobile_number = '$mobile_number'");
$row1 = mysql_fetch_array($qry1);
$mobile_number = $row1['mobile_number'];
$users[] = array('mobile_number' => $mobile_number );
return $users;
}
}
}
first, can you simplified the query something like this ?
$sql = "select a.*, b.mobile_number as user_mobile_number
from sent_invitations a
join users b on a.user_id = b.user_id";
or
$sql = "select a.*, b.mobile_number as user_mobile_number
from sent_invitations a
join users b on a.mobile_number = b.mobile_number";
it's depend on how this two tables can be related.
Now you can see if the sent_invitations.mobile_number also found in users.mobile_number just in one query. If this returns multiple same rows, then put distinct keyword after SELECT
second, back to your code, i think you should move return $users out form while block
while ($row = mysql_fetch_array($qry)) {
// your code
}
return $users;
good luck;
function invitation_result()
{
$this->load->database();
$user_id = $_GET['user_id'];
$qry = $this->db->query("select * from sent_invitations where user_id='$user_id'");
$results = $qry->result();
foreach ($results as $result)
{
$mobile_number = $result->mobile_number;
$qry1 = $this->db->query("select mobile_number from users where mobile_number = '$mobile_number'");
$results1 = $qry1->result();
foreach ($results1 as $result1)
{
$row1 = mysql_fetch_array($qry1);
$mobile_number = $result1->mobile_number;
$users = array('mobile_number' => $mobile_number );
return $users;
}
}
}

PHP Codeigniter Pagination

Hello i am stuck on codeigniter pagination.I am getting total rows 6, per page showing 2 row.
I am getting pagination link {Page: 1,2,3} where 1 is not clickable. On Clicking Page no:2 my link look like localhost/demo/index.php/home/press/?per_page=0/2 but i am getting error on sql
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/2,2' at line 1
SELECT * FROM media where media_type = 'PRESS' AND id <> 0 ORDER BY id DESC LIMIT 0/2
Same Error,pagintaion link getting when i click on link : 3
I dont know how to fix this issue.I am sharing my code which i used on my controller,model and view.
My controller code:
function press()
{
$this->load->model('Home_model');
$page= $this->input->get('per_page') ? $this->input->get('per_page') : 0;
$this->load->library('Pagination');
$data['page'] = $this->input->get('page');
if($data['page'] == '') {
$data['page'] = $config['per_page'] = '2'; // Per Page
} else {
$data['page'] = $config['per_page'] = $this->input->get('page');
}
$config['first_url']='0';
$pageno = $this->input->get('per_page');
if($pageno == ''){
$pageno = '0';
}
$url_to_paging = $this->config->item('base_url');
$config['base_url'] = $url_to_paging.'home/press/?per_page='.$page;
$return = $this->Home_model->pressdata($config['per_page'],$pageno, $data);
$data['pressdata'] = $return['result']; // Get Two Row Data
$config['total_rows'] = $return['count']; // Total Count 6
$this->pagination->initialize($config);
$this->load->view('press',$data);
}
Model :
function pressdata($pg_num, $offset, $content)
{
if($offset == ''){
$offset = '0';
}
$sql = "SELECT * FROM media where media_type = 'PRESS' AND id <> 0";
if($pg_num!=0 || $pg_num!="")
{
$sql .= " ORDER BY id DESC LIMIT ".$offset.",".$pg_num;
}
$query = $this->db->query($sql);
$sql_couint = "SELECT * FROM media where media_type = 'PRESS' AND id <> 0";
$query1 = $this->db->query($sql_couint);
$ret['result'] = $query->result();
$ret['count'] = $query1->num_rows();
return $ret;
}
Try it like this
$this->load->library('pagination');
$this->load->model('Home_model');
$config['base_url'] = base_url().'home/press/;
$config['total_rows'] = 200; // Total no of rows returned from the database table
$config['uri_segment'] = 3; // It is the page no,used as offset in model
$offset = 0;
if ($this->uri->segment($config['uri_segment']) != "") {
$offset = $this->uri->segment($config['uri_segment']);
}
$config['per_page'] = 20; // you can change it as you want
$return = $this->Home_model->pressdata($config['per_page'],$offset, $data);
$this->pagination->initialize($config);
In your model you can do something like this
function pressdata($per_page, $offset) {
if($per_page !== '' && $offset !== '') {
$this->db->limit($per_page, $offset);
}
//rest of your query
}
Don't copy paste it though, I just wanted to give you an idea. Modify it, implement it according to your needs. Let me know if it worked. Go through CodeIgniter's pagination library for more detailed documentation.
Finally i found the way to solve this problem.
Here are the final code for Controller, Model, View.
Controller Code :
function press()
{
$this->load->library('pagination');
$url_to_paging = $this->config->item('base_url'); // URL here (www.example.com)
$config['base_url'] = $url_to_paging.'home/press/'; // www.example.com/home/press
$config['per_page'] = '4'; // Per Page Data Show 4
$data = array();
$return = $this->Home_model->pressdata($config['per_page'],$this->uri->segment(3));
$data['pressdata'] = $return['result'];
$config['total_rows'] = $return['count'];
$this->pagination->initialize($config);
$this->load->view('press', $data);
}
Model Code :
function pressdata($num, $offset)
{
if($offset == '')
{
$offset = '0';
}
$sql = "SELECT * FROM media where media_type = 'PRESS' AND id <> 0 ";
if($num!='' || $offset!='')
{
$sql .= " order by id desc limit ".$offset.",".$num."";
}
$query = $this->db->query($sql);
$sql_count = "SELECT * FROM media WHERE media_type = 'PRESS' AND id <> 0";
$query1 = $this->db->query($sql_count);
$ret['result'] = $query->result_array();
$ret['count'] = $query1->num_rows();
return $ret;
}
View Page for pagination link :
if($this->pagination->create_links()) { ?>
<div style="clear:both; border-top: solid 1px #e9ecf1;"></div>
<div style="float:right;">
<span class="pagination" style="margin:0px; border:none;">
<?php echo $this->pagination->create_links(); ?>
</span>
</div>
<?php }
function pressdata($pg_num, $offset, $content)
{
if($offset == ''){
$offset = '0';
}
$sql = "SELECT * FROM media where media_type = 'PRESS' AND id => 0";
if($pg_num!=0 || $pg_num!="")
{
$sql .= " ORDER BY id DESC LIMIT ".$offset.",".$pg_num;
}
$query = $this->db->query($sql);
$sql_couint = "SELECT * FROM media where media_type = 'PRESS' AND id => 0";
$query1 = $this->db->query($sql_couint);
$ret['result'] = $query->result();
$ret['count'] = $query1->num_rows();
return $ret;
}
<-------id should be greater and equal to zero----->

PHP OOP number of results

Can someone tell me how to return the number of results if I use this function to grab data from the database? I have tried including this:
$this->number = $result->num_rows;
But that didn't do the trick. Also, if anyone can give me some advice to do the below code in a better way, that would be helpful too.
<?php
public function grabResults($table, $values = '*', $where = NULL, $field1 = NULL, $and = NULL, $field2 = NULL, $order = NULL)
{
$result = 'SELECT '.$values.' FROM '.$table;
if($where != NULL)
{
$result = 'SELECT '.$values.' FROM '.$table.' WHERE '.$field1.' = '.$where;
}
if($and != NULL)
{
$result = 'SELECT '.$values.' FROM '.$table.' WHERE '.$field1.' = '.$where.' AND '.$field2.' = '.$and;
}
if($order != NULL)
{
$result = 'SELECT '.$values.' FROM '.$table.' WHERE '.$field1.' = '.$where.' ORDER BY '.$order.' ASC';
}
$query = $this->data->mysqli->query($result);
if($query)
{
while($row = $query->fetch_assoc())
{
$rows[] = $row;
}
return $rows;
}
else {
return false;
}
}
?>
$result->num_rows;
sounds like a Codeigniter function that you tried to use in raw php.
Have you tried to count() the query?
$count=count($query);

fetch all rows from mysql db with php using aFetch($sql) problem

i inherited this code from some-one and this only returns the first row it finds:
function getMessages($userID, $from, $limit)
{
$id = $_SESSION['user_id'];
$sql = "SELECT * FROM rc_message_box_table WHERE profile_id_to = {$userID} AND rc_message_box_table.profile_id_from NOT IN (SELECT profile_id_block FROM rc_blocklist_table WHERE profile_id = {$id}) LIMIT {$from}, {$limit}";
$row = $this->aFetch($sql);
return $row;
}
function aFetch($sSql)
{
//print_r($sSql);
$aResults = array();
if(is_string($sSql))
{
$fnSql = $this->query($sSql);
}
while($row = mysql_fetch_assoc($fnSql))
{
$aResults[] = $row;
}
return $aResults;
}
how can i with this code return all rows where profile_id_to = {$userID} ??
thanks
function aFetch($result = false) {
if($result)
return mysql_fetch_assoc($result);
else
return mysql_fetch_assoc($this->result);
}
you can use this function.
Try removing the LIMIT clause:
SELECT *
FROM rc_message_box_table
WHERE profile_id_to = {$userID}
AND rc_message_box_table.profile_id_from NOT IN
(
SELECT profile_id_block
FROM rc_blocklist_table
WHERE profile_id = {$id}
)
Your result may be limited by $from, $limit parameters.
Look at the code where getMessages is being invoked, and analyse what values it is passing.

Categories