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

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;
}

Related

I am experiencing trouble with MySQL Update and i don't know how to fix it

I am new to MySQL. Here is my codeblock:
public function updateTable($obj, $column_names, $table_name, $bannerid) {
$c = (array) $obj;
$id = $bannerid;
$keys = array_keys($c);
$columns = '';
$values = '';
foreach($column_names as $desired_key){ // Check the obj received. If blank insert blank into the array.
if(!in_array($desired_key, $keys)) {
$$desired_key = '';
}else{
$$desired_key = $c[$desired_key];
}
$columns = $columns.$desired_key.',';
$values = $values."'".$$desired_key."',";
}
//$query = "INSERT INTO ".$table_name."(".trim($columns,',').") VALUES(".trim($values,',').")";
//mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = $id");
$query = "UPDATE ".$table_name." SET "."(".trim($columns,',').") = VALUES(".trim($values,',').")" ."WHERE id = '$id'" ;
$r = $this->conn->query($query) or die($this->conn->error.__LINE__);
if ($r) {
$new_row_id_update = $this->conn->insert_id;
return $new_row_id_update;
} else {
return NULL;
}
}
Here is the error I got:
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 '(image_url,intro) = VALUES('800bf5f59a1d13c8.jpg',',sd,cfcjaklewfh ewiuofejkfdh ' at line 1100
sgeddes is correct about the query structure. Try this one. You should echo out the $query to make sure it builds correctly.
public function updateTable($obj, $column_names, $table_name, $bannerid) {
$c = (array) $obj;
$id = $bannerid;
$keys = array_keys($c);
$subquery='';
foreach($column_names as $desired_key){
// Check the obj received. If blank insert blank into the array.
if(!in_array($desired_key, $keys)) {
$$desired_key = '';
}else{
$$desired_key = $c[$desired_key];
}
$subquery.=$desired_key."='".$$desired_key ."',";
}
//remove trailing common
$query="UPDATE ".$table_name." SET " substr(subquery,0,-1)." WHERE id = '$id'" ;
$r = $this->conn->query($query) or die($this->conn->error.__LINE__);
if ($r) {
$new_row_id_update = $this->conn->insert_id;
return $new_row_id_update;
} else {
return NULL;
}
}

only one element of every column is showing when I am fetching In array

When I am fetching data from database in array it's showing only one element of each column. I am using below query:
$stmt = $conn_obj->select(' user ',' * ',' status = "updated" ', $order=NULL, $group=null, $fromRecordNum.','.$recordsPerPage);
and select function is below:
private function tableExists($table) {
//$this->con = $this->createconnection();
$query = 'SHOW TABLES FROM ' . $this->db . ' LIKE "'.trim($table).'"';
//echo ''.$query;
$tablesInDb = mysqli_query($this->con, $query);
if ($tablesInDb) {
if (mysqli_num_rows($tablesInDb) == 1) {
//echo ''.mysqli_num_rows($tablesInDb);
return true;
}
else {
return false;
}
}
}
public function select($table, $row = '*', $where= null,$order=null,$group=null, $limit=null, $join=null){
//$this->con = $this->createconnection();
//echo $join;
$q = 'select'.$row.' from '.$table;
//print_r($q);
if($join != null){
$q .= ' join '.$join;
}
if($where != null){
$q .= ' where '.$where;
print_r($q);
}
if($group != null){
$q .= 'group by'.$group;
//print_r($q);
}
if($order != null){
$q .= 'order by'.$order;
}
if($limit != null){
$q .= 'limit '.$limit;
print_r($q);
}
if ($this->tableExists($table)) {
$query = mysqli_query($this->con, $q) or die(mysql_error());
//print_r($query);
if ($query) {
$this->numResults = mysqli_num_rows($query);
//echo $this->numResults;
for ($i = 0; $i < $this->numResults; $i++) {
$r = mysqli_fetch_array($query);
$key = array_keys($r);
for ($x = 0; $x < count($key); $x++) {
// Sanitizes keys so only alphavalues are allowed
if (!is_int($key[$x])) {
if (mysqli_num_rows($query) > 1)
$this->result[$i][$key[$x]] = $r[$key[$x]];
else if (mysqli_num_rows($query) < 1)
$this->result = null;
else
$this->result[$key[$x]] = $r[$key[$x]];
}
}
}
//print_r($this->result);
return $this->result;
} else {
return false;
}
} else{
return false;
}
}
I am fetching it with foreach loop as follow:
foreach($stmt as $row)
{
echo $row['user_Id'];
}
output is= 7 t : 2 2 2 u W u 2
and if I print whole array with print_r($row) then
output is= test ::1 2015-07-30 11:42:09am 2015-07-29 12:42:09pm 2015-07-30 12:28:57pm updated call_activated uninstall 2015-07-30 12:31:07pm.
If database has only one row with specified query then above problem is creating.
But in the case of two row with the specified query, its working fine as I want.
For multiple results, you are getting an array of arrays of elements.
For a single result, you are getting an array of elements.
So, for a single element, you have one foreach loop too many.
if in your example:
foreach($stmt as $row) {
echo $row['user_Id'];
}
Assuming $stmt contains the return value of your query:
foreach($stmt as $row) {
if (isset($row['user_Id'])) {
// do something with one single result record
} else {
foreach ($row AS $innerRow) {
// do something with each result record
}
}
}

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.

can anyone make this as a codeigniter format?

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()
}

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.

Categories