can anyone make this as a codeigniter format? - php

i am beginner in php and codeigniter.can anyone make this php programme as a codeigniter format?
if ($user_id > 0){
$follow = array();
$fsql = "select user_id from following
where follower_id='$user_id'";
$fresult = mysql_query($fsql);
while($f = mysql_fetch_object($fresult)){
array_push($follow, $f->user_id);
}
if (count($follow)){
$id_string = implode(',', $follow);
$extra = " and id in ($id_string)";
}else{
return array();
}

if ($user_id > 0)
{
$follow = array();
$qry = "select user_id from following where follower_id='$user_id'";
$res = $this->db->query(qry);
foreach($res->result() as $row)
{
array_push($follow, $row->user_id);
}
if (count($follow))
{
$id_string = implode(',', $follow);
$extra = " and id in ($id_string)";
}
else
{
return array();
}
}

Try this:
if ($user_id > 0){
$follow = array();
$rs = $this->db->select('user_id')->where('follower_id', $user_id)->get('following')->result_array();
if( is_array( $rs ) && count( $rs ) > 0 ){
$follow = array();
foreach( $rs as $key => $each ){
$follow[] = $each['user_id'];
}
}
if (count($follow)){
$id_string = implode(',', $follow);
$extra = " and id in ($id_string)";
}else{
return array();
}
}

This should be done in the model.
Using avtice record you can do it like this
function getFriends($user_id){
return $this->db
->select('user_id')
->where('follower_id',$user_id)
->get('following')
->result_array() // for single object use row_array()
}

Related

How to make a search webservice API with Codeigniter

I've made a Search API with native PHP in the past, but I don't know how to make it in Codeigniter. The code below is not showing the data. Could someone point me in the right direction?
public function peta(){
$data = array();
// $query = "select * from tb_peta";
$cari = isset($_REQUEST['cari']) ? $_REQUEST['cari'] : '';
if ($cari != null) {
$result = $this->db->query("SELECT * FROM tb_peta WHERE nama LIKE "."'%".$cari."%'");
} else {
$result = $this->db->query( "SELECT * FROM tb_peta");
}
// $q = $this->db->query($query);
if ($q -> num_rows() >0) {
$data ['success'] = 1;
$data ['message'] = 'data ada';
$data ['data']=$q->result();
} else {
$data['result']='0';
$data['message'] ='kosong';
}
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[] = $row;
}
echo json_encode(array('planet' => $json_response));
}
Make use of codeigniter query builder.
public function peta(){
$data = array();
$cari = isset($_REQUEST['cari']) ? $_REQUEST['cari'] : '';
if ($cari != null) {
$this->db->like('name',$cari,'both');
$result = $this->db->get("tb_peta");
} else {
$result = $this->db->get("tb_peta");
}
if ($result->num_rows() >0) {
$data ['success'] = 1;
$data ['message'] = 'data ada';
$data ['data']=$result->result_array();
} else {
$data['result']='0';
$data['message'] ='kosong';
}
echo json_encode(array('planet' => $data));
}

Cannot Use a Scalar Value as an Array, But Data Successfully Updated

I have this code :
public function updateSegmentGender ($product_id, $segment_gender) {
$this->connect();
$product_id = $this->escapeString($product_id);
$row_count = count($segment_gender);
for ($row = 0; $row < $row_count; $row++) {
$this->select('product_seg_gender', '*', NULL,
'product_id = "'.$product_id.'" AND gender = "'.$segment_gender[$row][0].'"', NULL, NULL);
$res = $this->getResult();
$res = count($res);
$gender = $segment_gender[$row][0];
$status = $segment_gender[$row][1];
if ($res <> 0) {
// UPDATE
$data = array ('status'=>$status);
$this->update('product_seg_gender', $data, 'product_id = "'.$product_id.'" AND gender = "'.$gender.'"');
}else {
// INSERT
$data = array ('product_id'=>$product_id, 'gender'=>$gender, 'status'=>$status);
$this->insert('product_seg_gender', $data);
}
}
}
and I'm using that method like this :
$user = new Product($db_server, $db_user, $db_password, $db_name);
$user->connect();
$segment_gender = array ( array ("all", "active"),
array ("female", "active"));
$res = $user->updateSegmentGender ('303', $segment_gender);
print_r($res);
but why I always got this error message :
Warning: Cannot use a scalar value as an array in /home/***/public_html/class/Database.class.php on line 130
however, the database is successfully updated. what did I do wrong?
UPDATE : here's complete line 97-145 of Database.class.php
// Function to SELECT from the database
public function select($table, $rows = '*', $join = null, $where = null, $order = null, $limit = null){
// Create query from the variables passed to the function
$q = 'SELECT '.$rows.' FROM '.$table;
if($join != null){
$q .= ' JOIN '.$join;
}
if($where != null){
$q .= ' WHERE '.$where;
}
if($order != null){
$q .= ' ORDER BY '.$order;
}
if($limit != null){
$q .= ' LIMIT '.$limit;
}
// echo $table;
$this->myQuery = $q; // Pass back the SQL
// Check to see if the table exists
if($this->tableExists($table)){
// The table exists, run the query
$query = $this->myconn->query($q);
if($query){
// If the query returns >= 1 assign the number of rows to numResults
$this->numResults = $query->num_rows;
// Loop through the query results by the number of rows returned
for($i = 0; $i < $this->numResults; $i++){
$r = $query->fetch_array();
$key = array_keys($r);
for($x = 0; $x < count($key); $x++){
// Sanitizes keys so only alphavalues are allowed
if(!is_int($key[$x])){
if($query->num_rows >= 1){
$this->result[$i][$key[$x]] = $r[$key[$x]];
}else{
$this->result[$i][$key[$x]] = null;
}
}
}
}
return true; // Query was successful
}else{
array_push($this->result,$this->myconn->error);
return false; // No rows where returned
}
}else{
return false; // Table does not exist
}
}
Note: I hope you require $res = $user->updateSegmentGender ('303', $segment_gender); need $data value and based on assumption I use $data for return part.
Perhaps due to $data not initialized. I'm trying to declaring the variable $data, as an array, before using it I also make another change that function updateSegmentGender() require return part so I put this.
public function updateSegmentGender ($product_id, $segment_gender) {
$this->connect();
$product_id = $this->escapeString($product_id);
$row_count = count($segment_gender);
$data = array();//Initialize variable...
for ($row = 0; $row < $row_count; $row++) {
$this->select('product_seg_gender', '*', NULL,
'product_id = "'.$product_id.'" AND gender = "'.$segment_gender[$row][0].'"', NULL, NULL);
$res = $this->getResult();
$res = count($res);
$gender = $segment_gender[$row][0];
$status = $segment_gender[$row][1];
if ($res <> 0) {
// UPDATE
$data = array ('status'=>$status);
$this->update('product_seg_gender', $data, 'product_id = "'.$product_id.'" AND gender = "'.$gender.'"');
}else {
// INSERT
$data = array ('product_id'=>$product_id, 'gender'=>$gender, 'status'=>$status);
$this->insert('product_seg_gender', $data);
}
}
//Return funal value in array format...
return $data;
}

getting information from database with php

I'm making API to simple forum ,,
Now trying to get the information from the Database and show it
on the control page :
showForums.php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TheForums</title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('fourmsAPI.php');
/*
function tinyf_forums_get($extra ='')
{
global $tf_handle;
$query = sprintf("SELECT * FROM `forums` %s",$extra );
$qresult = mysqli_query($tf_handle, $query);
if (!$qresult)
return NULL;
$recount = mysqli_num_rows($qresult);
if ($recount == 0)
return NULL ;
$forums = array();
for($i = 0 ; $i < $recount ; $i++)
$users[count($forums)] = mysqli_fetch_object($qresult);
//mysql_free_result($qresult);
return $forums;
}
*/
$forums = tinyf_forums_get();
if($forums == NULL)
{
die('problem');
}
$fcount = count($forums);
if($fcount == 0)
{
die('No Forums ');
}
?>
<ul type = "square">
<?php
for($i = 0 ; $i < $ucount ; $i++)
{
$forum = $forums[$i];
echo "<li><a href = \"forums.php?id=$forum->id\"> $forum->title <a/> <br/> $forum->desc <br/> </li>"; //$array ->
}
?>
</ul>
</body>
</html>
The Result ===> 'problem'
The Apifile:
fourmsAPI.php
<?php
//Forums APIs
function tinyf_forums_get($extra ='')
{
global $tf_handle;
$query = sprintf("SELECT * FROM `forums` %s",$extra );
$qresult = mysqli_query($tf_handle, $query);
if (!$qresult)
return NULL;
$recount = mysqli_num_rows($qresult);
if ($recount == 0)
return NULL ;
$forums = array();
for($i = 0 ; $i < $recount ; $i++)
$users[count($forums)] = mysqli_fetch_object($qresult);
//mysql_free_result($qresult);
return $forums;
}
function tinyf_forums_get_by_id($fid)
{
$id = (int)$fid;
if($fid == 0 )
return NULL ;
$result = tinyf_forums_get('WHERE id ='.$id);
if($result == NULL)
return NULL;
$forum = $result[0];
return $forum;
}
//get result is array()
function tinyf_forums_get_by_name($name)
{
global $tf_handle;
$n_name = mysqli_real_escape_string($tf_handle, strip_tags($name));
$result = tinyf_users_get("WHERE `name` = '$n_name'");
if ($result != NULL){
$user = $result[0];
}
else{
$user = NULL;
}
return $user ;
}
function tinyf_forums_get_by_email($email)
{
global $tf_handle;
$n_email = mysqli_real_escape_string($tf_handle, strip_tags($email));
$result = tinyf_users_get("WHERE `email` = '$n_email' ");
if ($result != NULL)
{
$user = $result[0];
}
else{
$user = NULL ;
}
return $user ;
}
function tinyf_forums_add($title,$desc)
{
global $tf_handle;
if ((empty($title)) || (empty($desc)))
return false;
$n_title = mysqli_real_escape_string($tf_handle, strip_tags($title));
$n_desc = mysqli_real_escape_string($tf_handle, strip_tags($desc));
$query = sprintf("INSERT INTO `forums` VALUE(NULL,'%s','%s')",$n_title,$n_desc);
$qresult = mysqli_query($tf_handle, $query);
if(!$qresult)
return false;
return true;
}
function tinyf_forums_delete($fid)
{
global $tf_handle;
$id = (int)$fid;
if($id == 0 )
return false ;
tinyf_forums_delete_all_posts($fid);
$query = sprintf ("DELETE FROM `forums` WHERE `id`= %d",$id);
$qresult = mysqli_query($tf_handle, $query);
if(!$qresult)
return false;
return true;
}
function tinyf_forums_update($fid,$title = NULL,$desc = NULL)
{
global $tf_handle;
$id = (int)$uid;
if($id == 0 )
return false ;
$forum = tinyf_forums_get_by_id($id);
if(!$forum)
return false;
if ((empty($title)) && (empty($desc)))
return false;
$fields = array() ;
$query = 'UPDATE `forums` SET ' ;
if(!empty($title))
{
$n_title = mysqli_real_escape_string($tf_handle, strip_tags($title));
$fields[count($fields)] = "`title` = '$n_title'";
}
if(!empty($desc))
{
$n_name = mysqli_real_escape_string($tf_handle,strip_tags($name));
$fields[count($fields)] = "`desc` = '$n_desc'";
}
for($i = 0; $i < $fcount ; $i++)
{
$query .= $fields[$i];
if($i != ($fcount - 1)) // i = 0 that the first element in the array .. 2 will be - 1 last 3shan hwa by3ed el array mn wa7ed :D
$query .=' , ';
}
$query .= ' WHERE `id` = '.$id;
$qresult = mysqli_query($tf_handle, $query);
if(!$qresult)
return false;
else
return true;
}
function tinyf_forums_delete_all_posts($fid)
{
global $tf_handle;
$id = (int)$fid;
if($id == 0){
return false;
}
$forums = tinyf_forums_get_by_id($id);
if(!$forum){
return false;
}
$topicsq = sprintf('SELECT * FROM `posts` WHERE `fid` = %d',$id) ;
$tresult = mysqli_query($tf_handle,$topicsq);
if(!$tresult){
return false;
}
$tcount = mysqli_num_rows($result);
for($i = 0; $i<$tcount ; $i++){
$topic = mysqli_fetch_object($tresult);
mysqli_query($tf_handle,'DELETE FROM `posts` WHERE `pid` = '.$topic ->id);
mysqli_query($tf_handle,'DELETE FROM `posts` WHERE `id` = '.$topic ->id);
}
mysqli_free_result($tresult);
return true ;
}
include ('db.php') ;
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
i expected it will show the information
i think the function tinyf_forums_get() is causing that
Your code is broken:
You define an array, then never use it:
$forums = array();
$users[count($forums)] = mysqli_fetch_object($qresult);
^^^^^---undefined, never returned, never used otherwise, therefore useless.
return $forums;
^^^^^^---returning permanently empty array
and since $forums is an empty array:
php > $x = array();
php > var_dump($x == null);
bool(true)
You probably want
if (count($forums) == 0)
instead.

Dynamically create a SQL statment from passed values in PHP

I am passing a number of values to a function and then want to create a SQL query to search for these values in a database.
The input for this is drop down boxes which means that the input could be ALL or * which I want to create as a wildcard.
The problem is that you cannot do:
$result = mysql_query("SELECT * FROM table WHERE something1='$something1' AND something2='*'") or die(mysql_error());
I have made a start but cannot figure out the logic loop to make it work. This is what I have so far:
public function search($something1, $something2, $something3, $something4, $something5) {
//create query
$query = "SELECT * FROM users";
if ($something1== null and $something2== null and $something3== null and $something4== null and $something5== null) {
//search all users
break
} else {
//append where
$query = $query . " WHERE ";
if ($something1!= null) {
$query = $query . "something1='$something1'"
}
if ($something2!= null) {
$query = $query . "something2='$something2'"
}
if ($something3!= null) {
$query = $query . "something3='$something3'"
}
if ($something4!= null) {
$query = $query . "something4='$something4'"
}
if ($something5!= null) {
$query = $query . "something5='$something5'"
}
$uuid = uniqid('', true);
$result = mysql_query($query) or die(mysql_error());
}
The problem with this is that it only works in sequence. If someone enters for example something3 first then it wont add the AND in the correct place.
Any help greatly appreciated.
I would do something like this
criteria = null
if ($something1!= null) {
if($criteria != null)
{
$criteria = $criteria . " AND something1='$something1'"
}
else
{
$criteria = $criteria . " something1='$something1'"
}
}
... other criteria
$query = $query . $criteria
try with array.
function search($somethings){
$query = "SELECT * FROM users";
$filters = '';
if(is_array($somethings)){
$i = 0;
foreach($somethings as $key => $value){
$filters .= ($i > 0) ? " AND $key = '$value' " : " $key = '$value'";
$i++;
}
}
$uuid = uniqid('', true);
$query .= $filters;
$result = mysql_query($query) or die(mysql_error());
}
// demo
$som = array(
"something1" => "value1",
"something2" => "value2"
);
search( $som );
Here's an example of dynamically building a WHERE clause. I'm also showing using PDO and query parameters. You should stop using the deprecated mysql API and start using PDO.
public function search($something1, $something2, $something3, $something4, $something5)
{
$terms = array();
$values = array();
if (isset($something1)) {
$terms[] = "something1 = ?";
$values[] = $something1;
}
if (isset($something2)) {
$terms[] = "something2 = ?";
$values[] = $something2;
}
if (isset($something3)) {
$terms[] = "something3 = ?";
$values[] = $something3;
}
if (isset($something4)) {
$terms[] = "something4 = ?";
$values[] = $something4;
}
if (isset($something5)) {
$terms[] = "something5 = ?";
$values[] = $something5;
}
$query = "SELECT * FROM users ";
if ($terms) {
$query .= " WHERE " . join(" AND ", $terms);
}
if (defined('DEBUG') && DEBUG==1) {
print $query . "\n";
print_r($values);
exit();
}
$stmt = $pdo->prepare($query);
if ($stmt === false) { die(print_r($pdo->errorInfo(), true)); }
$status = $stmt->execute($values);
if ($status === false) { die(print_r($stmt->errorInfo(), true)); }
}
I've tested the above and it works. If I pass any non-null value for any of the five function arguments, it creates a WHERE clause for only the terms that are non-null.
Test with:
define('DEBUG', 1);
search('one', 'two', null, null, 'five');
Output of this test is:
SELECT * FROM users WHERE something1 = ? AND something2 = ? AND something5 = ?
Array
(
[0] => one
[1] => two
[2] => five
)
If you need this to be more dynamic, pass an array to the function instead of individual arguments.

PHP - foreach how to store the array to mysql

I want to store array into mysql db something like this
item_row = nike,adidas,puma
qty_row = 1,3,2
total_row = 100,200,150
foreach
foreach ($_SESSION['order'] as $values) {
$item_name = $values['item-name'];
$item_qty = $values['item-qty'];
$item_price = $values['item-price'];
}
Let me know how to do that?
update
foreach ($_SESSION['order'] as $values) {
$item_name[] = $values['item-name'];
$item_qty[] = $values['item-qty'];
$item_price[] = $values['item-price'];
}
$item_row = implode(",", $item_name);
$qty_row = implode(",", $item_qty);
$total_row = implode(",", $item_price);
item_row = implode(',', $_SESSION['order']['item-name']);
qty_row = implode(',', $_SESSION['order']['item-qty']);
total_row = implode(',', $_SESSION['order']['item-price']);
I'm using a class to manage the connection to the data base and the query execution let me add it to you:
class DbConnection
{
var $ReturnQuery;
function Connect()
{
$connection = mysql_connect("serverName", "user", "password");
$DbSelect = mysql_select_db("databaseName", $connection);
if ($DbSelect)
return true;
else
return false;
}
function Execute($Query)
{
$ExecuteQuery = mysql_query($Query);
$affected = mysql_affected_rows();
if ($affected != -1)
{
if ($affected != 0)
{
if ($ExecuteQuery != 1)
{
while($row=mysql_fetch_assoc($ExecuteQuery))
{
$ResulArray[] = $row;
}
$this->ReturnQuery = $ResulArray;
}
return 1;
}
else
{
$this->ReturnQuery = '';
return 0;
}
}
else
{
$this->ReturnQuery = '';
return -1;
}
}
}
and then you can create instances to execute your query:
require_once('Includes/DbConnection.php');
$this->db = new DbConnection();
$this->db->Connect();
$query = "insert into items (item_name, item_qty, item_price) values ('".$item_name."', '".$item_qty."', '"$item_price"');
$query_safe = mysql_real_escape_string($query);
$this->db->Execute($query_safe);
I hope it helps!!
foreach ($_SESSION['order'] as $values) {
mysql_query('INSERT INTO tablename (name, qty, price) VALUES("'.$values['item-name'].'", "'.$values['item-qty'].'", "'.$values['item-price'].'"');
}

Categories