Call to a member function fetch_assoc() on a non-object - php

Here's my function:
function get_fname($un){
$registerquery = $this->conn->query("SELECT f_name FROM tz_members WHERE
usr='".$un."'");
while ($row = $registerquery->fetch_assoc()) {
return $fname = $row[$un];
}
}
Edit:
I chose to answer my own question because it has an editor.
#Mark Baker:
<?php
require_once 'Mysql.php';
$mysql = new Mysql();
?>
<html>
<head>
</head>
<body>
<h4><?php echo $mysql->get_fname("joann"); ?></h4>
</body>
</html>
That's how I am doing it...

It seems that your query failed. Because in that case query returns false. So try this:
$registerquery = $this->conn->query("SELECT f_name FROM tz_members WHERE
usr='".$un."'");
if ($registerquery) {
while ($row = $registerquery->fetch_assoc()) {
return $fname = $row[$un];
}
}
The failure may be caused by a syntax error in your query when $un contains characters that break the string declaration (like ' or \). You should use MySQLi::real_escape_string to escape that characters to prevent that.
Additionally, a function can only return a value once. So the while will be aborted after the first row.

$fname = $row[$un]; is assigning the value in $row[$un] to the variable $fname, then returning the result.
It's pointless doing that assignment to $fname because $fname is simply a local variable within the function.... if it's defined as global, then it's not good programming practise.
If echo $mysql->get_fname("joann") is the line where you're calling the get_fname() function, then how are you setting $mysql?
And what do you think will happen if the database query doesn't find any valid result for the query?

while ($row = fetch_assoc($registerquery)) {
return $fname = $row[$un];
}
}

Is it possible you forgot to give a table name in the connection?
$conn = new mysqli('localhost', 'root', 'password', 'ANY VALUE HERE??');

Related

Why mysql Insert into query not working in php application

When execute the query it's not working, it will print error. $q also not coming when i'm print it. but $_SESSION["username"]; is working?
<?php
session_start();
$_SESSION["username"];
include 'Db_Connection.php';
$q= $_GET[q];
$username= $_SESSION[username];
echo $username;
echo $q;
$sql="INSERT INTO search(searcher,searched_time,searched_email)
VALUES ('$username',NOW(),'$q')";
$result = mysqli_query($con,$sql);
if($result)
{
echo "Success";
}
else
{
echo "Error";
}
?>
Couple of things I can pick up from your provided code.
Your second line $_SESSION["username"]; is superfluous as it does nothing
You are using the mysql_* functions which are deprecated
You are not using prepared statements for inserting variables into your query
try something like this:
session_start();
//start assuming this is in your connection file
$con = new mysqli("db-ip-address", "db-user", "db-pass", "db-name")
//end assuming
$q= $_GET[q];
$username= $_SESSION[username];
echo $username;
echo $q;
$sql="INSERT INTO search(searcher,searched_time,searched_email) VALUES (?,NOW(),?)";
$stmt = $con->prepare($sql);
$stmt->bind_param("ss", $username, $q);
$result = $stmt->execute();
if($result) {
echo "Success";
} else {
echo "Error";
}
//remember to cleanup connections etc
as far as the value $q not printing out, make sure that the value is set via the GET query string http://someurl.com/somefile.php?q=some-value and that $q is not some weird non-printable value. If you want to confirm that the value is set, try running var_dump($_GET) to output the contents of your $_GET array to ensure there is actually a value being set.
I believe this is your problem:
$q= $_GET[q];
q should be surrounded in quotes, e.g.:
$q = $_GET['q'];
Other than that, what Damon said was completely correct.

Variable $connection is undefined. Impossible, what is happening there?

Objective: I am in the process of creating a php login script.
Problem: I can't seem to be able to make my includes recognize the $connection variable even though it should be clearly defined in connection.php. As a result the value of my variable is nothing / NULL.
What I tried: I started with mysql but quickly noticed that it was the wrong approach and converted my code to mysqli. I checked for typos in all the $connection variables I have. I made sure the paths are correct. As a last resort I did a Google search but didn't find an answer or any useful hint to my scenario.
Problem: What is the reason for my variable not being defined?
Error Messages:
All those messages are related to this single variable no being defined for some reason:
Php Notice: Undefined variable: connection in C:\xampp\htdocs\aspie\Php\Core\Common.php on line 4
Php Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\aspie\Php\Core\Common.php on line 4
Php Notice: Undefined variable: connection in C:\xampp\htdocs\aspie\Php\Core\Functions\Members.php on line 4
Php Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\aspie\Php\Core\Functions\Members.php on line 4
Php Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\aspie\Php\Core\Functions\Members.php on line 5
// INITIALIZER
<?php
session_start();
// error_reporting(NULL);
include 'Connection.php';
include 'Common.php';
include 'Functions/Members.php';
?>
**// ERROR MESSAGES **
<?php
$connection_error = 'Our website is experiencing technical issues, please come back later.';
$wrong_login = 'Password and name are wrong.';
$member_registered = 'Access has been denied. You do not seem to be a registered user.';
?>
**// CONNECTION **
<?php
include 'Errors.php';
$connection = mysqli_connect('localhost', 'root', '', 'project') or exit ($connection_error);
?>
**// COMMON **
<?php
error_reporting();
function sanitize($connection, $data) {
global $connection;
global $data;
return mysqli_real_escape_string($connection, $data);
}
?>
**// MEMBERS **
<?php
function member_registered($connection, $name) {
$name = sanitize($connection, $name);
$query = mysqli_query($connection, "SELECT COUNT(`id`) FROM `members` WHERE `name` = '$name'");
return (mysqli_num_rows($query) == 1) ? true : false;
}
?>
**// LOGIN **
<?php
include 'Php/Core/Initializer.php';
if (member_registered($connection, 'ee')) {
echo "exists";
}
die("eee");
echo error_reporting();
if (empty($_POST) == false) {
$name = $_POST['name'];
$password = $_POST['name'];
if (empty($name) OR empty($password)) {
echo $wrong_login;
}
else if (member_registered($connection, $name) == false) {
echo $member_registered;
}
}
?>
UPDATE:
Now what I get: existseee;
The conditional doesnt work now even though its all set up right. Username doesnt exist so it should'nt echo "exists:
if (member_registered($connection, 'ee')) {
echo "exists";
}
die("eee");
In your case, the $connection variable inside your sanitize function isn't reachable.
Try to pass the $connection variable into your function, like this:
function sanitize($data, $connection) {
return mysqli_real_escape_string($connection, $data);
}
Read more about it here: http://php.net/manual/en/language.variables.scope.php
UPDATE
In **// MEMBERS ** you need to include the new parameter as well:
function member_registered($name, $connection) {
$name = sanitize($name, $connection);
$query = mysqli_query($connection, "SELECT COUNT(`id`) FROM `members` WHERE `name` = '$name'");
return (mysqli_num_rows($query) == 1) ? true : false;
}
and because of that your **// LOGIN ** should be updated as well:
include 'Php/Core/Initializer.php';
if (member_registered('ee', $connection)) {
echo "exists";
}
die("eee");
echo error_reporting();
if (empty($_POST) == false) {
$name = $_POST['name'];
$password = $_POST['name'];
if (empty($name) OR empty($password)) {
echo $wrong_login;
}
else if (member_registered($name, $connection) == false) {
echo $member_registered;
}
}
And make sure that the $connection variable is reachable everywhere where you need it.
UPDATE #2
Answer to your update:
it should be like this:
if (member_registered('ee', $connection)) {
echo "exists";
}
and not like this:
if (member_registered($connection, 'ee')) {
echo "exists";
}
the $connection is the second parameter.

accessing connection variable in a while loop

I am trying to acces my connection variable while I run a while loop, yet when I try to call a function, it bogus out on me and PHP gives me the so called boolean error when I try to prepare my statement within the function.
I debugged it to the point that I know my variable $CategorieId is being pushed on and I do get a array return of $con when I do a print_r in the function itself. However when I try to acces it when I prepare my statement, it just returns me a boolean, thus creating the error in the dropdown, not being able to fill it up.
The setup is as followed.
dbControl.php
$con = mysqli_connect('localhost','root','','jellysite') or die("Error " . mysqli_error($con));
function OpenConnection(){
global $con;
if (!$con){
die('Er kan geen verbinding met de server of met de database worden gemaakt!');
}
}
functionControl.php
function dropdownBlogtypeFilledin($con,$CategorieId){
echo "<select name='categorie' class='dropdown form-control'>";
$sql = "SELECT categorieId, categorieNaam
FROM categorie";
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_execute($stmt1);
mysqli_stmt_bind_result($stmt1,$categorieId,$categorieNaam);
while (mysqli_stmt_fetch($stmt1)){
echo "<option value='".$categorieId."'.";
if( $categorieId == $CategorieId){
echo "selected='selected'";
}
echo ">".$categorieNaam."</option>";
}
echo "</select>";
}
Blogedit.php
<?php
require_once '../db/dbControl.php';
require_once '../db/functionControl.php';
session_start();
OpenConnection();
$id = $_SESSION['user'];
?>
// some html up to the while loop
<?php
$a = $_GET['a'];
$sql = "SELECT blog.blogId,
blog.blogTitel,
blog.blogCategorieId,
blog.blogSynopsis,
blog.blogInhoud
FROM blog
WHERE blog.blogId = ? ";
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt1,'i',$a);
mysqli_stmt_execute($stmt1);
mysqli_stmt_bind_result($stmt1, $blogId, $Titel, $CategorieId, $Synopsis, $Inhoud );
while (mysqli_stmt_fetch($stmt1)){
$Synopsis = str_replace('\r\n','', $Synopsis);
$Inhoud = str_replace('\r\n','', $Inhoud);
?>
// again some HTML
<?php dropdownBlogtypeFilledIn($con,$CategorieId); ?>
// guess what, more html!
<?php
}
?>
Does anyone know how I can solve it? I tried it with the global variable (the OpenConnection() function) but it didn't seem to work.
Edit
I confirm it has indeed to do with the $con variable. I tested it by defining the $con variable again in the function, and it printed perfectly what I wanted. Its a bad solutions. I just prefer to have it defined once.
The weird thing is that it happens only when i put it in a while loop. I have a create form which is exactly the same, except there is no while loop, since I create it all from scratch and there is no PHP involved on that part. I have there a dropdown function as well, which also requires the $con variable, but there it works. I really think it has to do with the while loop.
I solved it for now by creating a new instance of the connection variable before i initiated the prepared statement of the page retrieving the information.
<?php
$connection = $con;
$a = $_GET['a'];
$sql = "SELECT blog.blogId,
blog.blogTitel,
blog.blogCategorieId,
blog.blogSynopsis,
blog.blogInhoud
FROM blog
WHERE blog.blogId = ? ";
mysqli_stmt_init($con);
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt1,'i',$a);
mysqli_stmt_execute($stmt1);
mysqli_stmt_bind_result($stmt1, $blogId, $Titel, $CategorieId, $Synopsis, $Inhoud );
mysqli_stmt_store_result($stmt1);
while (mysqli_stmt_fetch($stmt1)){
$Synopsis = str_replace('\r\n','', $Synopsis);
$Inhoud = str_replace('\r\n','', $Inhoud);
<?php dropdownBlogtypeFilledIn($connection ,$CategorieId); ?>
?>
With the variable $connection I could initiate the function that required the connection details within the while call. I am not sure if there is a cleaner option here, but indeed I read somewhere that I couldn't use the same connection variable if I am already using it in a prepared statement. Appearantly I cannot ride this one the same connection variable, and that seemed to be the problem. I will look into this and hope I dont have to write a while bunch of connection variables whenever I have multiple dropdowns for example that pull information from the database.

php4: wrong parameter count for mysql_query?

Not sure how much context I can provide. I just tried to do overdue homework and I get the error: Its supposed to be a simple login page, login check and loginsuccess and failure.
on check.php:
Warning: Wrong parameter count for mysql_query() in /u/students/j/j.d.dancks/public_html/cis231/hw/hw5/check.php on line 11
I thought I knew what I was doing I guess not.
code:
<?php
$good = false;
if(array_key_exists('nick',$_POST)&&array_key_exists('pass',$_POST))
{
if(isset($_POST['nick'])&&isset($_POST['pass']))
{
$con = mysql_connect('localhost','heh','heh');
mysql_select_db('heh_db',$con);
$q = mysql_query(sprintf("select * from reg_users where username='%s' and pass='%s'",
mysql_real_escape_string($_POST['nick']),
mysql_real_escape_string($_POST['pass'])),$con) or die(mysql_query());
if(mysql_num_rows($q)==1)
{
$good=true;
$r = mysql_fetch_assoc($q);
session_start();
$_SESSION['user'] = $r['username'];
$_SESSION['lastlogin'] = time();
mysql_close($con);
header('loginsuccess.php');
}
else
{
header('loginfailure.html');
}
}
else
{
header('hw5.html');
}
}
if(!$good)
{
header('hw5.html');
}
?>
You need at least a query parameter for mysql_query(). I believe what you want is mysql_error().
change or die(mysql_query()) to or die(mysql_error())
2nd mysql_query() has no parameter
try using another concatenation technique.
$nick = mysql_real_escape_string($_POST['nick']);
$pass = mysql_real_escape_string($_POST['pass']);
$query = "select * from reg_users where username='".$nick."' and pass='".$pass."'";
$q = mysql_query($query,$con) or die(mysql_query());

PHP Code Problem

function check_login($array_val)
{
$strQury = "Select * from tblsignup where usr_email ='".$array_val[0]."' and usr_password = '".$array_val[1]."'" ;
$result = mysql_query($strQury);
$row_user = mysql_fetch_array($result);
if(mysql_num_rows($result)>0)
{
$msg = "true";
}
else
{
$msg = "false";
}
return $msg ;
}
The return value is Object id #1true???? what is object id#1?
Change from:
echo $objUser.check_login($array_login);
to:
echo $objUser->check_login($array_login);
The . operator in PHP does string concatenation, while the arrow allows you to access object methods and attributes.
You're returning the strings "true" or "false" when you probably mean the boolean values true and false.
Oh, and your code is wide open to a visit from Little Bobby Tables. You really should use mysqli and proper prepared statements instead.
Try this:
function check_login($array_val)
{
$strQury = "Select * from tblsignup where usr_email ='".$array_val[0]."' and usr_password = '".$array_val[1]."'" ;
$result = mysql_query($strQury);
$row_user = mysql_fetch_array($result);
if(mysql_num_rows($result)>0)
{
return true;
}
else
{
return false;
}
}
Let us know what result you get when using that code.
user single quotes and things will start to work better. also check your query for sql injection bug as it does have it.
Change
echo $objUser.check_login($array_login);
to
echo $objUser;
echo check_login($array_login);
You should end up with the following result:
Object id #1
true
My guess is that $objUser was set earlier with something along these lines:
$objUser = new User;
As a result, it is an object (the first one declared) and will return Object id #1 when you just echo it. You will need to read up on classes to understand that more.

Categories