create function in php include while loop - php

i have this code to call posts from database
<?php
$q = "SELECT * FROM posts WHERE user_id = '$user_info[id]' ORDER BY id DESC";
$r = mysqli_query($dbc, $q);
while($post_info = mysqli_fetch_assoc($r)) { ?>
//html
it works fine but i like to create a function includes the query and the while loop and move it to functions.php and keep the html code in template.php but I don't know how with the while loop..
function data_post($dbc, $user_info['id']){
$q = "SELECT * FROM posts WHERE user_id = '$user_info[id]' ORDER BY id DESC";
$r = mysqli_query($dbc, $q);
while($post_info = mysqli_fetch_assoc($r))
return $post_info
}
I have tried this but there is no result

function ss()
{
...........
while($post_info = mysqli_fetch_assoc($r))
{
$new_array[]=$post_info;
}
return $new_array;
}
And return the $new_array outside of the while loop
And get the value like this
$mm= ss();
print_r($mm); here you get that $new_array values

Try this:
Function Body
function data_post($dbc, $user_id){
$q = "SELECT * FROM posts WHERE user_id = '$user_id' ORDER BY id DESC";
$r = mysqli_query($dbc, $q);
$arrayPost = array();
while($post_info = mysqli_fetch_assoc($r)){
$arrayPost[] = array('id' => $post_info['postId'], 'name' => $post_info['postName']);
// or whatever data you want to return of post, insert in array
}
return $arrayPost;
}
Function Calling
$userPostArray = data_post($dbc, $user_info['id']);

Related

How to make this function from while in php

I have this code which bring a single post from my database depend on id
global $connect;
$id = $_GET['id'];
$sql_query="SELECT * FROM `topics` WHERE id = {$id}";
$result = mysqli_query($connect,$sql_query);
while ($row = mysqli_fetch_assoc($result)) { ....}
How can i make this as function (My try) :
Function get_single_post($id) {
global $connect;
$id = (int)$id;
$sql_query="SELECT * FROM `topics` WHERE id = {$id}";
$result = mysqli_query($connect,$sql_query);
while ($row = mysqli_fetch_assoc($result)) {
$post[] = $row;
}
return $post;
}
to use this function i use this :
get_single_post($_GET['id']);
and when i call something i use :
$post['title']; for title as ex
Remember, a function returns a value, but that value must be assigned to a variable for you to be able to access it.
$post = get_single_post($_GET['id]);
Using the above should now allow you to access the post as you expect.
If your id is primary key than you don't need while loop as it will return only one result
modified function
Function get_single_post($id) {
global $connect;
$id = (int)$id;
$sql_query="SELECT * FROM `topics` WHERE id = {$id}";
$result = mysqli_query($connect,$sql_query);
return mysqli_fetch_assoc($result);
}

Search results with pagination code won't return results

I'm having a hard time getting this search results with pagination code to work. It does successfully grab the search keyword entered in the html form on another page and brings it into this search.php page. if I echo $search I see the keyword on the page. But I get no results even though I should for the query. Can anyone see what might be going on?
require "PDO_Pagination.php";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
echo $search;
$pagination->rowCount("SELECT * FROM stories WHERE stories.genre = $search");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories WHERE stories.genre = $search ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
else
{
$pagination->rowCount("SELECT * FROM stories");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
$query = "SELECT * FROM stories";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
$query .= " WHERE genre LIKE '%$search%'";
}
// No need for else statement.
$pagination->rowCount($query);
$pagination->config(3, 5);
$query .= " ORDER BY SID ASC LIMIT {$pagination->start_row}, {$pagination->max_rows}";
$stmt = $connection->prepare($query);
$stmt->execute();
$model = $stmt->fetchAll();
var_dump($model);
In your query do:
WHERE stories.genre LIKE '%string%');
instead of:
WHERE stories.genre = 'string');
Because the equals will want to literally equal the field.

how to return value of selected id in database php

I insert in the database a csv file. how will i return the id and use it to insert in another table. it always displays array to string conversion errror. is there something wrong with "return"
here is my controller
public function uploadThree(){
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
while(($fileop = fgetcsv($handle,1000,",")) !==false)
{
$appname = $fileop[0];
$servname = $fileop[1];
$ciname = $fileop[2];
$servid = $this->some_model->insertBulkServ($servname); //i tried to get the value here then insert below
$appid = $this->some_model->insertBulkSingleApp($appname);//i tried to get the value here then insert below
$this->some_model->insertBulkCI($ciname);
$this->some_model->ASMAP($appid,$servid);
}
if($success == TRUE)
redirect(base_url().'some_controller/uploadPage');
}
MODEL
public function insertBulkServ($service) {
/* Inserts csv file for a service */
$service = $this->db->escape_str($service);
$queryStr = "Select service from appwarehouse.service where service = '$service' and VISIBILITY = 'VISIBLE'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
$queryStr = "SELECT id FROM appwarehouse.service WHERE service='$service' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
//in here how do i get the ID how do i return it
}else{
$queryStr = "INSERT INTO appwarehouse.service(service) VALUES ('$service');";
$query = $this->db->query($queryStr);
$queryStr = "SELECT id FROM appwarehouse.service WHERE service='$service' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
}
}
public function insertBulkSingleApp($app_name) {
/* Inserts csv file for an application */
$app_name = $this->db->escape_str($app_name);
$queryStr = "Select * from appwarehouse.application_table where app_name = '$app_name' and VISIBILITY = 'VISIBLE'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
$queryStr = "SELECT id FROM appwarehouse.application_table WHERE app_name='$app_name' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
}
else{
$queryStr = "INSERT INTO appwarehouse.application_table(app_name)
VALUES ('$app_name');";
$query = $this->db->query($queryStr);
$queryStr = "SELECT id FROM appwarehouse.application_table WHERE app_name='$app_name' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
}
}
public function ASMAP($appid,$servid) {
$appid = $this->db->escape_str($appid);
$servid = $this->db->escape_str($servid);
$queryStr = "Select * from appwarehouse.app_service where app_id = '$appid' AND serv_id = '$servid' and VISIBILITY = 'VISIBLE'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
return true;
}
else{
$queryStr = "INSERT INTO appwarehouse.app_service(app_id,serv_id)
VALUES ('$appid','$servid');";
$query = $this->db->query($queryStr);
return true;
}
}
What you probably want is:
$this->db->insert_id()
The insert ID number when performing database inserts.
More Info: http://ellislab.com/codeigniter/user-guide/database/helpers.html
You need to do it it is very simple
After the query insert
$queryStr = "INSERT INTO appwarehouse.service(service) VALUES ('$service');";
Instead of select use this
return $this->db->insert_id();
Or if you really need to return the object
$queryStr = "SELECT id FROM appwarehouse.application_table WHERE app_name='$app_name' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
Return id instead of object
return $query->row()->id;
One more thing to note. insert_id is the last inserted id so you dont have to run select query to get id.
Also use row() to select single record. result() selects multiple records so you will get an array. see here.

Function inside while inside function inside while only triggers once each layer

Consider this (simplified) code... Function getLevelOne is called, runs fine, calls getLevelTwo, runs fine, and then stops, without continuing the while that was called in getLevelOne... The way its written, you'd assume that the second function would be called for each number in $list1 (2,4,5,6)... Am I missing something?
$list1 = "2,4,5,6";
$table1 = 'thistable';
getLevelOne($list1, $table1);
function getLevelOne($list1, $table1){
$q = "select * from $table1 where id IN ('$list1')";
$r = mysqli_query($db, $q);
while($row = mysqli_fetch_array($r)){
echo 'oh';
$table2 = 'nexttable';
$list2 = $row[$table2];
getLevelTwo($list2, $table2);
}
}
function getLevelTwo($list2, $table2){
$q2 = "select * from $table2 where id IN ('$list2')";
$r2 = mysqli_query($db, $q2);
while($row2 = mysqli_fetch_array($r2)){
echo 'shit';
}
}

PHP - how to use array in function?

I get an array of values returned from the following function:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
I now want to use these values in a new function, where each "user_id" is used to collect text from the database through this function:
function get_text($writer) {
$writer = mysql_real_escape_string ($writer);
$sql = "SELECT * FROM `text` WHERE user_id='$writer' ORDER BY timestamp desc";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
However the returned value from the first function is an array, and as I've learnt the hard way, arrays cannot be treated by "mysql_real_escape_string".
How can I make the second function handle the values that I got from the first function?
Any responses appreciated.
Thank you in advance.
Your first mistake is to use mysql_fetch_assoc when only selecting one column. You should use mysql_fetch_row for this. This is likely going to fix your primary problem.
Could look like this:
$subs = get_subscribitions($whateverId);
$texts = get_text($subs);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_row($result)) {
$user_id = $row['user_id'];
$rows[$user_id] = $user_id;
}
mysql_free_result($result);
return $rows;
}
function get_text($writer) {
$writers = implode(",", $writer);
$sql = "SELECT * FROM `text` WHERE user_id IN ({$writers}) ORDER BY timestamp DESC";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
This will save you a lot of time, because you can get all data from 'text' in one statement.
The solution is to avoid placing arrays in your $rows array in the first function. Instead of:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
try:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
This will place only the value from column 'user_id' in the $rows array.
In order to use the second function you must iterate over the array returned from the first one. Something like this could work for you:
$user_subscriptions = get_subscribitions($user);
foreach($user_subscriptions as $subscription) {
$texts = get_text($subscription['user_id']);
foreach($texts as $text) {
// do something with the fetched text
}
}
As George Cummins says,
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
and, to speed up the second function:
function get_text($writer)
{
$sql = "SELECT * FROM `text` WHERE user_id in (".implode(',',$writer).") ORDER BY timestamp desc";
$rows = array();
if ($result = mysql_query($sql))
{
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
mysql_free_result($result);
}
return $rows;
}
The change to the query means that you only do one in total rather than one for each ID thus removing the time taken to send the query to the server and get a response multiple times. Also, if the query fails, the function returns an empty array
Use :
string implode ( string $glue , array $pieces )
// example, elements separated by a comma :
$arrayasstring = impode(",", $myarray);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$row = mysql_fetch_row($results);
mysql_free_result($result);
return intval($row['user_id']);
}
it return only the user id you can used it in the 2nd function

Categories