MySQL Query: Trying to get property of non-object - php

I'm getting following error message.
Notice: Trying to get property of non-object in
C:\xampp\htdocs\my\include\user_functions.php on line 34
Here is my Code
$conn = db_connection();
if($conn == false) {
user_error('Unable to connect to database');
return false;
}
$query = "UPDATE user SET passwd = '".$new_passwd."'
WHERE username = '".$username."' ";
$result=$conn->query($query);
if($result == false) {
user_error('Query Error'.$conn->error);
return false;
}
if($result->num_rows == 1) {
echo 'Password changed';
} else {
echo 'Failed ';
}
here is my db_connection
function db_connection() {
$db = new mysqli('localhost','root','','php_login');
if(!$db) {
echo 'Could not connect to database server';
} else {
return $db;
}
}

The UPDATE statement doesn't return a result set. What are you trying to get from fetch_array?

UPDATE
class mysqli{
public $aff_num_rows;
//some properties
//some properties
//some methods
//some methods
public function query($sql)
{
$resultset = mysql_query($sql); //after query instantiate the $aff_numrows
//property with function
$this->aff_num_rows = mysql_affected_rows(); //guess you are using sqlite
//so you might have different function
//and you can use this property
}
}
And in you code you have
if($conn->aff_num_rows == 1) {
echo 'password changed';
} else {
echo 'error changing pasword';
}

Related

how to insert a query within a class?

I am working on a class where I want to check if everything is filled in and if everything is filled in then insert into the database, but I am stuck on how I can insert within my class so I hope you guys could help me. I never got any errors of this problem.
Here is the code:
<?php
class clsCatCheck
{
private $catName;
public function __construct($catName)
{
$this->setCatName($catName);
}
public function setCatName($catName)
{
$connect = new PDO('mysql:host=hostname;dbname=dbname', "username", "password");
$select = $connect->prepare('SELECT * FROM category');
$row = $select->fetch();
if (isset($_POST['addCat'])) {
if (empty($_POST['catName'])) {
throw new Exception('Geen categorienaam is ingevuld<br />');
}
//if (strlen($_POST['catName'] <= 4)) {
// throw new Exception('De categorienaam moet minimaal 4 letters of langer zijn<br />');
//}
if ($_POST['catName'] == $row[1]) {
throw new Exception('Deze categorienaam bestaat al<br />');
}
}
else {
$query = $connect->prepare("INSERT INTO category (catName) VALUES (:catName = catName)");
$query->bindParam(':catName', $_POST['catName'] ,PDO::PARAM_STR);
$query->execute();
}
$this->catName = $catName;
}
public function getCatName()
{
return $this->catName;
}
}
Already thanks for helping.
If you want more code from me just ask.
You are not binding parameters correctly.
Corrected code:
$query = $connect->prepare("INSERT INTO category (catName) VALUES (:catName)");
$query->bindParam(':catName', $_POST['catName'] ,PDO::PARAM_STR);

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, object given

I have splitted my php into 2/3 pieces using (MySQLi Procedural) :
First is dedicated to db (open,execute,Total Row, Affected Row,Close..)
Second is dedicated to other functionalities .
Here is an example :
db.php (First)
<?php
class DB {
var $DBUser = 'myuser';
var $DBPass = 'mypassword';
var $DBServer = 'localhost';
var $DBName = 'myDB';
var $con;
function __construct() {
$testcon = mysqli_connect($this->DBServer, $this->DBUser, $this->DBPass,$this->DBName);
if (!$testcon) {
die('Database connection failed: ' . mysqli_connect_error());
} else {
$this->con = $testcon;
}
}
function Qry($sql) {
if($result = mysqli_query($this->con,$sql) ) {
return $result;
}
else
{
$err = "Error: ".$sql. " :: ". mysqli_error;
die("$err");
}
}
function TotRows($result) {
if($result === false)
{
die("Error ".mysqli_error);
}
else return mysqli_num_rows($result);
}
function AffRows($result) {
return mysqli_affected_rows($result);
}
function LastRow($tblName) {
return mysqli_insert_id($this->con);
}
function close() {
mysqli_close($this->con);
}
}
?>
and
functions.php (Second)
public function GetBoolResult($db,$sql) {
$result=$db->Qry($sql);
$no_of_rows = $db->TotRows($db->con);
if ($no_of_rows > 0) {
// user exist
return true;
} else {
// user does not exist
return false;
}
}
When I try to execute the script I got the following Warning error :
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, object given in db.php
if you look at this function to get number of rows , the parameter is tested inside the function, the sql statement has been tested directly in the mysql serverwithout any error.
Any idea what's the problem ?
Don't you wan't to pass in the result, not the connection
$result = $db->Qry($sql);
$no_of_rows = $db->TotRows($result);

MYSQLi - Commands out of sync error

Got some code here. Been stuck on it for ages and I can't seem to get around the error.
<?PHP
error_reporting(E_ALL);
ini_set('display_errors',1);
$mysqli = new mysqli('localhost', 'username', 'password', 'table');
$statsObjects = array();
$collatedObjects = array();
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
Global $areRows;
$areRows = 2;
if( $result = $mysqli->query("SELECT * FROM stats WHERE collated = 0", MYSQLI_USE_RESULT) )
{
while($row = $result->fetch_assoc())
{
array_push($statsObjects,
new Statistic(
$row['ID'],
$row['player_GUID'],
$row['shots_fired'],
$row['shots_hit'],
$row['damage_done'],
$row['damage_taken'],
$row['friendly_damage_done'],
$row['friendly_damage_taken']
));
}
$success = true;
} //end if
$result->free_result();
if($success)
{
foreach($statsObjects as $stat)
{
$statsGuid = $stat->getGuid();
$query = "SELECT COUNT(*) AS total FROM collatedStats WHERE player_GUID = '" . $statsGuid . "'";
if( $result2 = $mysqli->query($query, MYSQLI_USE_RESULT) )
{
$value = $result2->fetch_assoc();
$rows = $value['total'];
if($rows > 0)
{
$areRows = 1;
}
else
{
$areRows = 0;
}
}
else
{
echo("Error <br/>");
echo($mysqli->error);
}
if($areRows == 1)
{
echo("Found a row! <br/>");
}
elseif($areRows == 0)
{
Echo("No rows found. =) <br/>");
}
} //end foreach
}
//OBJECT
class Statistic
{
var $GUID;
var $shotsfired;
var $shotshit;
var $damagedone;
var $damagetaken;
var $friendlydamagedone;
var $friendlydamagetaken;
var $ID;
function Statistic($ID, $GUID, $fired, $hit, $ddone, $dtaken, $fddone, $fdtaken)
{
$this->id = $ID;
$this->GUID = $GUID;
$this->shotsfired = $fired;
$this->shotshit = $hit;
$this->damagedone = $ddone;
$this->damagetake = $dtaken;
$this->friendlydamagedone = $fddone;
$this->friendlydamagetaken = $fdtaken;
}
function getID()
{
return $this->ID;
}
function getGuid()
{
return $this->GUID;
}
function getShotsFired()
{
return $this->shotsfired;
}
function getShotsHit()
{
return $this->shotshit;
}
function getDamageDone()
{
return $this->damagedone;
}
function getDamageTaken()
{
return $this->damagetaken;
}
function getFriendlyDDone()
{
return $this->friendlydamagedone;
}
function getFriendlyDTaken()
{
return $this->friendlydamagetaken;
}
function getAccuracy()
{
if($shotsfired == 0)
{
$accuracy = 0;
}
else
{
$accuracydec = $shotshit / $shotsfired;
$accuracy = $accuracydec * 100;
}
return $accuracy;
}
}
Basically every time i run the code, it keeps coming up with the error "Commands out of sync; you can't run this command now". I've spent 2 days trying to fix it - following peoples instructions about freeing the result before running the next one. I even used a prepared statement in previous code however it didn't work either - this is newly written code in an attempt to get it working. All the reading i've done suggests that this error happens when you try to run an sql command while another one is still receiving data - however i've called my first query, stored it all in an array - and then i'm looping through the array to get the next lot of data..and that's giving me an error, which is where i'm getting confused.
Any help would be appreciated!
Thank You to #andrewsi for his help - it turns out that having the MYSQLI_USE_RESULT inside SELECT * FROM stats WHERE collated = 0", MYSQLI_USE_RESULT was giving me the error. Removing that allowed me to do my code normally.
Hopefully this helps others that may have the same problem. =)

Undefined variables errors

So i'm working on a project and i am running to to a few mysql & php errors.
First Error :
This is all code associated with First Error
// Database Class
class Database {
public $_link, $_result, $_numRows;
public function __construct($server, $username, $password, $db){
$this->_link = mysql_connect($server, $username, $password) or die('Cannot Execute:'. mysql_error());
mysql_select_db($db, $this->_link);
}
public function disconnect(){
mysql_close($this->_link);
}
public function query($sql){
$this->_result = mysql_query($sql, $this->_link) or die('Cannot Execute:'. mysql_error());
$this->_numRows = mysql_num_rows($this->_result);
}
public function numRows() {
return $this->_numRows;
}
public function rows(){
$rows = array();
for($x = 0; $x < $this->numRows(); $x++) {
$rows[] = mysql_fetch_assoc($this->_result);
}
return $rows;
}
}
// Setup.php
$is_set = 'false';
global $company_name, $ebay_id;
if( isset($_POST['ebay_id'], $_POST['company_name']) ){
$_ebay_id = $_POST['ebay_id'];
$_company_name = $_POST['company_name'];
$is_set = 'true';
} else {
// Silence is Golden!
}
$_service_database = new Database('localhost', 'root', 'password', 'chat-admin');
$_service_database->query("SELECT * FROM installs WHERE `identity` = '$mysqldb' AND `db_name` = '$mysqldb'");
if ($_service_database->numRows() == 0){
if($is_set == true){
$_service_database->query("INSERT INTO installs (ebay_id, name, db_name, identity) VALUES ('$_ebay_id', '$_company_name', '$mysqldb', '$mysqldb')");
}
} else {
// header("Location: index.php");
}
$_service_database->disconnect();
?>
<form name="setup" method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<input placeholder="eBay Username" type="text" name="ebay_id">
<input placeholder="Company Name" type="text" name="company_name">
<input type="hidden" name="insert" value="true">
<input type="submit">
</form>
So what this does is checks if the variables defined are in the database if they are not then when the form is submitted it inserts our values, if they are in the database it redirects to index.php, ok so i am receiving the all mighty MySQL num_rows* expects parameter 1 to be resource, boolean given ..., now i have searched everywhere and only found that the die error should solve, that is why you can see it on line 16 in the function query, now although i get the error everything still works its not really good for me to turn error reporting off so any help would be great. Also if you see undefined variables like $mysqldb they are actually set but on a different page and they are valid
Second Error : = function made for simplicity of a templating system
This is all associated with Second Error
function get_content_type($value){
if (strpos($value,'title:') === 0 ) {
$title = explode("title: ",$value);
$value = $title[1];
} else if (strpos($value,'css:') === 0 ) {
$css = explode("css: ",$value);
$value = $css[1];
} else if (strpos($value, 'js:') === 0 ) {
$javascript = explode("js: ", $value);
$value = $javascript[1];
} else {
// Silence is Golden
}
if($value == $title[1]){
echo '<title>'.$value.'</title>';
} else if ($value == $css[1]) {
echo '<link rel="stylesheet" href="'.$value.'">';
} else if ($value == $javascript[1]) {
echo '<script src="'.$value.'"></script>';
}
}
// Calling
get_content_type('title: Welcome to my site');
get_content_type('css: http://something.com/style.css');
get_content_type('js: http://code.jquery.com/jquery-latest.min.js');
everything works as this outputs
<title>Welcome to my site</title><link rel="stylesheet" href="http://somesite.com/style.css"><script src="http://code.jquery.com/jquery-latest.min.js"></script>
Only when i set error_reporting(0);
The errors i get are undefined variables because obviously i'm setting one, then im unsettling that one and setting the other so eventually only 1 is true although its already outputted all of them correctly.
UPDATE
Second Error : Errors =
Notice: Undefined variable: css in C:\Server\www\hidie\libs\test.php on line 19
Notice: Undefined variable: title in C:\Server\www\hidie\libs\test.php on line 17
Notice: Undefined variable: title in C:\Server\www\hidie\libs\test.php on line 17
First Error : Errors =
ERROR: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given
Ok so here's your problem:
First, as mentioned in the comment, mysql_num_rows only works on select and show. You have it in your query method, which is called by an insert. You can't do that.
public function query($sql){
$this->_result = mysql_query($sql, $this->_link) or die('Cannot Execute:'. mysql_error());
$this->_numRows = mysql_num_rows($this->_result); // <- BAD!
}
You call it on this line:
if($is_set == true){
$_service_database->query("INSERT INTO installs (ebay_id, name, db_name, identity) VALUES ('$_ebay_id', '$_company_name', '$mysqldb', '$mysqldb')");
}
You could make a second method for database and call it for all calls that write to the db:
public function execute($sql){
$this->_result = mysql_query($sql, $this->_link) or die('Cannot Execute:'. mysql_error());
}
which would be called like so:
if($is_set == true){
$_service_database->execute("INSERT INTO installs (ebay_id, name, db_name, identity) VALUES ('$_ebay_id', '$_company_name', '$mysqldb', '$mysqldb')");
}
Second, you need to implicitly define the variables $css and $title outside of those conditionals. Otherwise you are attempting to call undefined vars as indicated by the message...
$title = "";
$css = "";
if (strpos($value,'title:') === 0 ) {
$title = explode("title: ",$value);
$value = $title[1];
} else if (strpos($value,'css:') === 0 ) {
$css = explode("css: ",$value);
$value = $css[1];
} else if (strpos($value, 'js:') === 0 ) {
$javascript = explode("js: ", $value);
$value = $javascript[1];
} else {
// Silence is Golden
}

PHP Class Function Ignores Return Statement

For some reason the return doesn't work when the check_em() succeeds. I'm new to php, so I'm at a loss here.
<?php
//Class to handle mysql
class db_handler {
private $db_host = 'localhost';
private $db_name = 'project';
private $db_user = 'project';
private $db_pass = 'dbpassword';
private $db_con_mysql = '';
private $db_con_db = '';
public function check_em($username, $password) {
$db_query = "SELECT password FROM user WHERE name='".$username."' LIMIT 1;";
if($this->db_con_mysql!='') {
$db_query_response = mysql_query($db_query) or die('Query failed: '.mysql_error());
$db_query_return = mysql_fetch_row($db_query_response);
$db_sha1_hash = $db_query_return[0];
echo $db_sha1_hash."<br>";
echo sha1($password)."<br>";
if(sha1($password)==$db_sha1_hash) {
return 'user valid'; //THIS DOESN'T WORK!?!?!?
} else {
return 'no good';
}
} else {
$this->db_connect();
$this->check_em($username, $password);
}
}
//Connect to mysql, then database
private function db_connect() {
$this->db_con_mysql = mysql_connect($this->db_host, $this->db_user, $this->db_pass) || die('Connection failed: '.mysql_error());
$this->db_con_db = mysql_select_db($this->db_name) || die('Could not use'.$this->db_name.'. '.mysql_error());
return;
}
//Disconnect from database and reset vars used to track connection.
private function db_disconnect() {
if($this->db_con_mysql!='') {
mysql_close();
$this->db_con_mysql = '';
$this->db_con_db = '';
return;
}
}
public function fake($some_val) {
if($some_val<6) {
return TRUE;
} else {
return FALSE;
}
}
}
$db_obj = new db_handler();
$val1 = $db_obj->check_em('someuser','password'); //should return 'user valid'
echo "val1:".$val1."<br>";
echo "<br><br>";
$val2 = $db_obj->check_em('someuser','passw0rd'); //should return 'no good'
echo "val2:".$val2."<br>";
echo "<br><br>";
echo "test<br>";
echo $db_obj->fake(4)."<br>";
?>
Results:
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
val1:
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
7c6a61c68ef8b9b6b061b28c348bc1ed7921cb53
val2:no good
test
1
This line needs a return:
return $this->check_em($username, $password);
But a more sensible solution would be to connect to the database inside the if when the connection is null. Really, the whole thing could be better written, but I'll leave it at that.
...
else {
$this->db_connect();
return $this->check_em($username, $password);
}
...
You want to add the return, so that if it fails, then it goes one level deeper and finds another. If that level deeper succeeds, it passes the value up to the level above, which can pass it up and up until it reaches the original function call.

Categories