Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Here is the Code, from where error is coming :)
I hope that I'll get my answer quick!!!
function getSubs($id, $type, $start = null) {
if($type == 0) {
if(is_numeric($start)) {
if($start == 0) {
$start = '';
} else {
$start = 'AND `relations`.`id` < \''.$this->db->real_escape_string($start).'\'';
}
$limit = 'LIMIT '.($this->s_per_page + 1);
}
$query = sprintf("SELECT * FROM `relations`, `wp_users` WHERE `relations`.`subscriber` = '%s' AND `relations`.`leader` = `wp_users`.`ID` $start ORDER BY `relations`.`id` DESC $limit", $this->db->real_escape_string($id));
} else {
if(is_numeric($start)) {
if($start == 0) {
$start = '';
} else {
$start = 'AND `relations`.`id` < \''.$this->db->real_escape_string($start).'\'';
}
$limit = 'LIMIT '.($this->s_per_page + 1);
}
$query = sprintf("SELECT * FROM `relations`, `wp_users` WHERE `relations`.`leader` = '%s' AND `relations`.`subscriber` = `wp_users`.`ID` $start ORDER BY `relations`.`id` DESC $limit", $this->db->real_escape_string($id));
}
$result = $this->db->query($query);
while($row = $result->fetch_assoc()) {
$array [] = $row;
}
return array($array, $total = $result->num_rows);
}
function getActions($id, $likes = null, $type = null) {
global $LNG;
if($type == 1) {
$verify = $this->verifyLike($id);
$result = $this->db->query(sprintf("SELECT * FROM `messages`, `wp_users` WHERE `id` = '%s' AND `messages`.`uid` = `wp_users`.`ID`", $this->db->real_escape_string($id)));
if($result->num_rows == 0) {
return $LNG['like_message_not_exist'];
}
if(!$verify) {
$stmt = $this->db->prepare("INSERT INTO `likes` (`post`, `by`) VALUES ('{$this->db->real_escape_string($id)}', '{$this->db->real_escape_string($this->id)}')");
$stmt->execute();
$affected = $stmt->affected_rows;
$stmt->close();
if($affected) {
$this->db->query("UPDATE `messages` SET `likes` = `likes` + 1, `time` = `time` WHERE id = '{$this->db->real_escape_string($id)}'");
$user = $result->fetch_assoc();
$insertNotification = $this->db->query(sprintf("INSERT INTO `notifications` (`from`, `to`, `parent`, `type`, `read`) VALUES ('%s', '%s', '%s', '2', '0')", $this->db->real_escape_string($this->id), $user['uid'], $user['id']));
if($this->email_like) {
if($user['email_like'] && ($this->id !== $user['ID'])) {
sendMail($user['user_email'], sprintf($LNG['ttl_like_email'], $this->username), sprintf($LNG['like_email'], realName($user['user_login'], $user['first_name'], $user['last_name']), $this->url.'/index.php?a=profile&u='.$this->username, $this->username, $this->url.'/index.php?a=post&m='.$id, $this->title, $this->url.'/index.php?a=settings&b=notifications'), $this->email);
}
}
}
} else {
$x = 'already_liked';
}
} elseif($type == 2) {
$verify = $this->verifyLike($id);
$result = $this->db->query(sprintf("SELECT `id` FROM `messages` WHERE `id` = '%s'", $this->db->real_escape_string($id)));
if($result->num_rows == 0) {
return $LNG['like_message_not_exist'];
}
if($verify) {
$stmt = $this->db->prepare("DELETE FROM `likes` WHERE `post` = '{$this->db->real_escape_string($id)}' AND `by` = '{$this->db->real_escape_string($this->id)}'");
$stmt->execute();
$affected = $stmt->affected_rows;
$stmt->close();
if($affected) {
$this->db->query("UPDATE `messages` SET `likes` = `likes` - 1, `time` = `time` WHERE id = '{$this->db->real_escape_string($id)}'");
$this->db->query("DELETE FROM `notifications` WHERE `parent` = '{$this->db->real_escape_string($id)}' AND `type` = '2' AND `from` = '{$this->db->real_escape_string($this->id)}'");
}
} else {
$x = 'already_disliked';
}
}
if($likes == null) {
$query = sprintf("SELECT `likes` FROM `messages` WHERE `id` = '%s'", $this->db->real_escape_string($id));
$result = $this->db->query($query);
$get = $result->fetch_row();
$likes = $get[0];
}
$verify = $this->verifyLike($id);
if($verify) {
$state = $LNG['dislike'];
$y = 2;
} else {
$state = $LNG['like'];
$y = 1;
}
if($this->l_per_post) {
$query = sprintf("SELECT * FROM `likes`,`wp_users` WHERE `post` = '%s' and `likes`.`by` = `wp_users`.`ID` ORDER BY `likes`.`id` DESC LIMIT %s", $this->db->real_escape_string($id), $this->db->real_escape_string($this->l_per_post));
$result = $this->db->query($query);
while($row = $result->fetch_assoc()) {
$array[] = $row;
}
$people = '';
foreach($array as $row) {
$people .= '<img src="'.$this->url.'/thumb.php?src='.$row['image'].'&w=25&h=25&t=a" title="'.realName($row['user_login'], $row['first_name'], $row['last_name']).' '.$LNG['liked_this'].'" /> ';
}
}
$actions = '<a onclick="doLike('.$id.', '.$y.')" id="doLike'.$id.'">'.$state.'</a> - <a onclick="focus_form('.$id.')">'.$LNG['comment'].'</a> - <a onclick="share('.$id.')">'.$LNG['share'].'</a> <div class="like_btn" id="like_btn'.$id.'"> '.$people.$likes.'</div>';
if(empty($this->id)) {
$actions = ''.$LNG['login_to_lcs'].' <div class="like_btn"> '.$people.$likes.'</div>';
}
if(isset($x)) {
return $LNG["$x"].' <div class="like_btn"> '.$likes.'</div>';
}
return $actions;
}
The notice "Trying to get property of non-object" couldn't be more clear. You are trying to read a property of something that is not an object.
For example:
$object = false;
echo $object->property; // Notice: Trying to get property of non-object
Probably it is happening because you are assuming every SQL query you are doing is succeeding. But if a SQL query has errors and fails to run, the call returns false instead of a results object.
Sinse you didn't even say what line you are having this problem it's not worth the effort of helping you any further here. Check if your queries are suceeding before trying to use the result and read the MySQL error message from $this->db->error to figure out whats going wrong.
Related
The expected behaviour of the code is
dynamically assign value to array (this is done a few times) and then print it
Code:
$PLLinks = array();
$sql245 = "SELECT `Username`, `Password`, `MacAddress` FROM `Users` WHERE `Username` LIKE '$guestUsername' AND `Password` LIKE '$guestPassword' AND `MacAddress` LIKE '$guestMacAddress'";
$result4 = mysql_query($sql245);
if (mysql_num_rows($result4) == 1) {
for ($i = 0; $i<count($Checknames); $i++)
{
if ($PLNames[$i] == 'Valid' && $PLChecked[$i] == 'Invalid'){
$result = mysql_query("SELECT `Link` FROM `Checksums` WHERE `Name` LIKE '$ValidNames[$i]' LIMIT 1");
$value = mysql_fetch_object($result);
$PLChecked[] = $value->{'Link'};
echo $value->{'Link'};
}
else if ($PLNames[$i] == 'Valid' && $PLChecked[$i] != 'Invalid') {
$PLLinks[] = 'noUpd';
}
else if ($PLNames[$i] != 'Valid') {
$PLLinks[] = 'Remove';
}
}
echo implode(',', $PLLinks);
// this should print "a,b,c" but instead it prints "abc"
}
If the solution is simple, please hint it only.
Thanks
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;
}
Hi, I have a question, when i ever insert this code
if ($pointsreach>=$tempunilevel ){
mysql_query("UPDATE `incentives_table` SET pointsreach = pointsreach +500 where userid = '$newsponsorid' ");
the if statement does not work anymore
if (count($items) >0 && $lev <= 10 ){ // found get sponsor id for the next computation
$sponsorid = $items->upline; //sponsor id
but when i remove the
if ($pointsreach>=$tempunilevel ){
mysql_query("UPDATE `incentives_table` SET pointsreach = pointsreach +500 where userid = '$newsponsorid' ");
the statement works perfectly ...
$query = " UPDATE `#__eds_incentives_table` SET `temp` = `temp` + 25 where `userid` = '$sponsorid' ";
$db->setQuery($query);
$db->query();
$mote = $this->entryuni($sponsorid, $lev + 1, +25);
}
else {
return 'ok';
}
This is the code
public function entryuni($newsponsorid = null, $lev = 2, $fpv = 0)
{
$db = & JFactory::getDBO();
$query = "SELECT upline,fslot FROM `table` where userid = '$newsponsorid' ";
$db->setQuery($query);
$items = $db->loadObject();
$items = (!empty($items)) ? $items : array();
$queryreach = mysql_query("SELECT * FROM incentives_table WHERE userid = '$newsponsorid' ");
$fetchreach = mysql_fetch_array($queryreach);
$pointsreach=$fetchreach['pointsreach'];
$tempunilevel=$fetchreach['temp_unilevel'];
if ($pointsreach>=$tempunilevel ){
mysql_query("UPDATE `incentives_table` SET pointsreach = pointsreach +500 where userid = '$newsponsorid' ");
if (count($items) >0 && $lev <= 10 ){ // found get sponsor id for the next computation
$sponsorid = $items->upline; //sponsor id
$query = " UPDATE `#__eds_incentives_table` SET `temp` = `temp` + 25 where `userid` = '$sponsorid' ";
$db->setQuery($query);
$db->query();
$mote = $this->entryuni($sponsorid, $lev + 1, +25);
}
else {
return 'ok';
}
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);
Here's my deal:
I found a simple ACL, and have absolutely fallen in love with it. The problem? It's all in mysql, not mysqli. The rest of my site is written in mysqli, so this bothers me a ton.
My problem is that the ACL can easily connect without global variables because I already connected to the database, and mysql isn't object oriented.
1) Is it needed to convert to mysqli?
2) How can I easily convert it all?
Code:
<?
class ACL
{
var $perms = array(); //Array : Stores the permissions for the user
var $userID = 0; //Integer : Stores the ID of the current user
var $userRoles = array(); //Array : Stores the roles of the current user
function __constructor($userID = '')
{
if ($userID != '')
{
$this->userID = floatval($userID);
} else {
$this->userID = floatval($_SESSION['userID']);
}
$this->userRoles = $this->getUserRoles('ids');
$this->buildACL();
}
function ACL($userID = '')
{
$this->__constructor($userID);
//crutch for PHP4 setups
}
function buildACL()
{
//first, get the rules for the user's role
if (count($this->userRoles) > 0)
{
$this->perms = array_merge($this->perms,$this->getRolePerms($this->userRoles));
}
//then, get the individual user permissions
$this->perms = array_merge($this->perms,$this->getUserPerms($this->userID));
}
function getPermKeyFromID($permID)
{
$strSQL = "SELECT `permKey` FROM `permissions` WHERE `ID` = " . floatval($permID) . " LIMIT 1";
$data = mysql_query($strSQL);
$row = mysql_fetch_array($data);
return $row[0];
}
function getPermNameFromID($permID)
{
$strSQL = "SELECT `permName` FROM `permissions` WHERE `ID` = " . floatval($permID) . " LIMIT 1";
$data = mysql_query($strSQL);
$row = mysql_fetch_array($data);
return $row[0];
}
function getRoleNameFromID($roleID)
{
$strSQL = "SELECT `roleName` FROM `roles` WHERE `ID` = " . floatval($roleID) . " LIMIT 1";
$data = mysql_query($strSQL);
$row = mysql_fetch_array($data);
return $row[0];
}
function getUserRoles()
{
$strSQL = "SELECT * FROM `user_roles` WHERE `userID` = " . floatval($this->userID) . " ORDER BY `addDate` ASC";
$data = mysql_query($strSQL);
$resp = array();
while($row = mysql_fetch_array($data))
{
$resp[] = $row['roleID'];
}
return $resp;
}
function getAllRoles($format='ids')
{
$format = strtolower($format);
$strSQL = "SELECT * FROM `roles` ORDER BY `roleName` ASC";
$data = mysql_query($strSQL);
$resp = array();
while($row = mysql_fetch_array($data))
{
if ($format == 'full')
{
$resp[] = array("ID" => $row['ID'],"Name" => $row['roleName']);
} else {
$resp[] = $row['ID'];
}
}
return $resp;
}
function getAllPerms($format='ids')
{
$format = strtolower($format);
$strSQL = "SELECT * FROM `permissions` ORDER BY `permName` ASC";
$data = mysql_query($strSQL);
$resp = array();
while($row = mysql_fetch_assoc($data))
{
if ($format == 'full')
{
$resp[$row['permKey']] = array('ID' => $row['ID'], 'Name' => $row['permName'], 'Key' => $row['permKey']);
} else {
$resp[] = $row['ID'];
}
}
return $resp;
}
function getRolePerms($role)
{
if (is_array($role))
{
$roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` IN (" . implode(",",$role) . ") ORDER BY `ID` ASC";
} else {
$roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` = " . floatval($role) . " ORDER BY `ID` ASC";
}
$data = mysql_query($roleSQL);
$perms = array();
while($row = mysql_fetch_assoc($data))
{
$pK = strtolower($this->getPermKeyFromID($row['permID']));
if ($pK == '') { continue; }
if ($row['value'] === '1') {
$hP = true;
} else {
$hP = false;
}
$perms[$pK] = array('perm' => $pK,'inheritted' => true,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']);
}
return $perms;
}
function getUserPerms($userID)
{
$strSQL = "SELECT * FROM `user_perms` WHERE `userID` = " . floatval($userID) . " ORDER BY `addDate` ASC";
$data = mysql_query($strSQL);
$perms = array();
while($row = mysql_fetch_assoc($data))
{
$pK = strtolower($this->getPermKeyFromID($row['permID']));
if ($pK == '') { continue; }
if ($row['value'] == '1') {
$hP = true;
} else {
$hP = false;
}
$perms[$pK] = array('perm' => $pK,'inheritted' => false,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']);
}
return $perms;
}
function userHasRole($roleID)
{
foreach($this->userRoles as $k => $v)
{
if (floatval($v) === floatval($roleID))
{
return true;
}
}
return false;
}
function hasPermission($permKey)
{
$permKey = strtolower($permKey);
if (array_key_exists($permKey,$this->perms))
{
if ($this->perms[$permKey]['value'] === '1' || $this->perms[$permKey]['value'] === true)
{
return true;
} else {
return false;
}
} else {
return false;
}
}
function getUsername($userID)
{
$strSQL = "SELECT `username` FROM `users` WHERE `ID` = " . floatval($userID) . " LIMIT 1";
$data = mysql_query($strSQL);
$row = mysql_fetch_array($data);
return $row[0];
}
}
?>
Just add a $mysqli property to this class and have the MySQLi object passed to it in constructor.
class ACL {
private $mysqli;
public function __construct(MySQLi $mysqli) {
$this->mysqli = $mysqli;
/* rest of your code */
}
}
The rest is pretty much search and replace.
The code is written to support PHP4. That tells me two things: firstly, the author couldn't use mysqli even if he wanted to, because PHP4 didn't have it, and secondly, the code is probably pretty old, and was written before the PHP devs started really trying to push developers to use mysqli instead of mysql.
If it's well written, then converting it to use mysqli instead should be a piece of cake. The API differences between mysql and mysqli at a basic level are actually pretty minimal. The main difference is the requirement to pass the connection object to the query functions. This was optional in mysql and frequently left out, as it seems to have been in this code.
So your main challenge is getting that connection object variable to be available wherever you make a mysqli function call. The easy way to do that is just to make it a property of the class, so it's available everywhere in the class.
I also recommend you drop the other php4 support bits; they're not needed, and they get in the way.