Using SQL in a function - php

I'm trying to create a function in PHP that connects to SQL with the global $conn, and another which authenticates the user. However, referencing the SQL connection function in the second function isn't working.
Error:
Fatal error: Call to a member function query() on a non-object in /[...]/functions.php on line [see below]
SQLinfo.php contains valid database information, in the form of constants SQLurl, SQLuser, SQLpass & SQLdatabase.
Code:
function SQLconnect(){
require 'SQLinfo.php';
global $conn;
$conn = new mysqli(SQLurl,SQLuser,SQLpass,SQLdatabase);
if($conn->connect_error){
return $conn->connect_error;
}else{
return True;
}
}
function isauthenticated($username,$token){
if(empty($username) || empty($token)){
return False;
}else{
SQLconnect();
//error line:
$result = $conn->query("SELECT * FROM `userdata` WHERE `username` = '".$username."' AND `lastid` = '".$token."'");
if($result->num_rows == 1){
return True;
}else{
return False;
}
$result->free;
}
}
I tried looking at this answer, however since the mysql extension is deprecated and the global has been defined I couldn't figure it out. I'd appreciate any help.

Related

PHP PDO: Call to a member function fetch() on boolean

So I'm currently trying to do a PDO SELECT Request, but when executing and fetching the extracted data, this error shows up:
1 - Fatal error: Uncaught Error: Call to a member function fetch() on boolean in C:\wamp64\www\NewKali\includes\user.inc.php on line 53
2 - Error: Call to a member function fetch() on boolean in C:\wamp64\www\NewKali\includes\user.inc.php on line 53
This is where I call the function:
include 'includes/user.inc.php';
$userOBJ = new User;
if($userOBJ->isAdmin($_SESSION['session_u-name'])){
AdminControl();
}
Code:
public function isAdmin($user){
$userToGet = $user;
$stmt = $this->Connect()->prepare("SELECT * FROM user_secure WHERE username_db=?");
$query1 = $stmt->execute([$userToGet]);
if(!$query1)
{
die("Execute query error, because: ". print_r($this->Connect()->errorInfo(),true) );
}else{
foreach ($query1->fetch() as $row) {
if($row['admin_db'] == 1){
return true;
} else {
return false;
}
}
}
}
The first error says that I'm not handling the PDO errors, which I think that I'm already handling any PDO error in my code, but somehow still gets detected as I'm not doing so... (Correct me if wrong)
Second error states that calling PDO->fetch() is returning a boolean, but I'm requesting data, so it's not able to continue with the following code...
I don't get why this is showing... The "username_db" var in the query is the same as the one that I have in my DB.
In the same file as the function above, I have this next function and when called, it does fine
public function RegisterUser($user, $pwd, $mail){
$u_Insert = $user;
$p_Insert = $pwd;
$m_Insert = $mail;
$stmt = $this->Connect()->prepare("INSERT INTO user_secure(username_db, password_db) VALUES (?,?)");
$query1 = $stmt->execute([$u_Insert, $p_Insert]);
$stmt = $this->Connect()->prepare("INSERT INTO user_info(mail_db) VALUES (?)");
$query2 = $stmt->execute([$m_Insert]);
if($query2 && $query1){
return true;
} else {
return false;
}
}
Is there something that I'm missing?
I have already checked this thread but I'm still in the exact position...
Thank you for your time
(I'm still learning PDO, sorry if my code isn't clean)
This line here is one of the reasons. execute returns true or false indicating if the query succeeded or failed.
$query1 = $stmt->execute([$userToGet]);
In a sense, $query1 is a boolean.
Now in these lines, you are trying to access the fetch method from $query1 which is a boolean.
foreach ($query1->fetch() as $row) {
if($row['admin_db'] == 1){
return true;
} else {
return false;
}
}
To get the row, you need to write it like this:
$results = $stmt->fetch();
or in your case:
foreach ( $stmt->fetch() as $row) {
if($row['admin_db'] == 1){
return true;
} else {
return false;
}
}

Why is this php function causing a sever 500 error?

I'm trying to implement these two functions in a separate file functions.php and call it in index.php
function is_field($column, $table, $requested) {
$is_field_query = "SELECT ".$column." FROM ".$table." WHERE ".$column."='".$requested."'";
$is_field_result = $mysqli->query($is_field_query);
$is_true = $is_field_result->num_rows;
$is_field_result->close();
return $is_true;
}
function get_content($column, $table, $requested) {
$get_content_query = "SELECT ".$column." FROM ".$table." WHERE ".$column."='".$requested."'";
$get_content_result = $mysqli->query($get_content_query);
$get_content_row = $get_content_result->fetch_array(MYSQLI_ASSOC);
$get_content_content = $get_content_row["content"];
$get_content_result->close();
return $content;
}
I have tried it over and over again and I have no idea why it wont work. The first one is returning 1 for valid or 0 for invalid. The second retrieves the content from a specific cell in the MySQL table. Any help would be much appreciated.
You're using $mysqli inside the function, but you never pass the MySQLi resource itself. Consider writing your function like this:
function is_field($mysqli, $column, $table, $requested) {
Or, create a class that takes a MySQLi resource and reference it with $this->mysqli inside your function.
Also, code like this may be another issue:
$is_field_result = $mysqli->query($is_field_query);
$is_true = $is_field_result->num_rows;
You're not checking whether $is_field_result is false; therefore, the next statement causes a fatal error, because a property can't be fetched from something that's not an object.
if (($is_field_result = $mysqli->query($is_field_query)) === false) {
die($mysqli->error);
}
$is_true = $is_field_result->num_rows;
It turns out the reason it was not working was I needed to add an extra field into the function to accept the passing of $mysqli from the connection.
function is_field($mysqli, $column, $table, $requested) {
$is_field_query = "SELECT * FROM $table WHERE $column='$requested'";
if (($is_field_result = $mysqli->query($is_field_query)) == false) {
die($mysqli->error);
}
$is_true = $is_field_result->num_rows;
$is_field_result->close();
return $is_true;
}
function get_content($mysqli, $column, $table, $requested) {
$get_content_query = "SELECT * FROM $table WHERE $column='$requested'";
if (($get_content_result = $mysqli->query($get_content_query)) == false) {
die($mysqli->error);
}
$get_content_row = $get_content_result->fetch_array(MYSQLI_ASSOC);
$get_content = $get_content_row["content"];
$get_content_result->close();
return $get_content;
}

PHP PDO CRUD class Call to a member function rowCount() on a non-object

I'm just getting started using PDO to move away from mysqli but hit a problem. I'm following a tutorial and I want to return an array from the database but I get the following error:
Fatal error: Call to a member function rowCount() on a non-object in C:\xampp\htdocs\phptuts\crud\core\managedb.class.php on line 27
Here is my managedb.php class:
<?php
class ManageDatabase
{
public $link;
function __construct()
{
include_once('database.class.php');
$conn = new database;
$this->link = $conn->connect();
return $this->link;
}
function getData($table_name, $id=null)
{
if(isset($id))
{
$query = $this->link->query("SELECT * FROM $table_name WHERE id = '$id' ORDER BY id ASC");
}
else
{
$query = $this->link->query("SELECT * FROM $table_name ORDER BY id ASC");
}
$rowCount = $query->rowCount();
if($rowCount >= 1)
{
$result = $query->fetchAll();
}
else
{
$result = 0;
}
return $result;
}
}
Then I'm simply using the following code to try and get a response:
<?php
include_once('../core/managedb.class.php');
$init = new ManageDatabase;
$table_name = 'users';
$data = $init->getData($table_name);
print_r($data);
This is when I get the error, Any ideas?
I'd var_dump($query) before the $rowCount = $query->rowCount(); line to see what it actually is, because apparently it's not an object. I'm guessing it's either NULL or empty because the whole $this-link->query(<sql statement>); didn't return what you expected
A couple of things to check out:
From the PHP manual:
PDO::query() returns a PDOStatement object, or FALSE on failure.
You'll want to test if the query succeed and if not, why. You can check the error using PDO's errorInfo function:
if ($query == false)
{
print_r($this->link->errorInfo());
exit();
}
Another thing to note is that rowCount() in PDO returns the affected rows from a INSERT / UPDATE / DELETE type statement. For a SELECT you may get a row count, or you may not. The manual suggests a separate query to find the number of rows, but in your instance it might be easier testing if you get anything back from fetchAll():
$result = $query->fetchAll();
if (!empty($result))
{
return $result;
}
else
{
return 0;
}

PHP Post variable not working

I am sending data to a PHP script using an android app. The following is the PHP script.
telejoke.php:
<?php
include 'JokeValidation.php';
include 'DBConnect.php';
$username = $_POST['username'];
$joke = $_POST['joke'];
$dbname = 'Telejoke';
mysql_select_db($dbname);
if (validate()){
$query = "INSERT INTO jokes (username, joke) VALUES ('$username','$joke')";
mysql_query($query) or die('Error, insert query failed');
}
mysql_close($conn);
?>
jokevalidation.php:
<?php
include 'DBConnect.php';
$dbname = 'telejoke';
mysql_select_db($dbname);
function validate(){
if ($joke == null) return false;
else if($username == null) return false;
return true;
}
?>
For some reason, the PHP script will put the data into the database when I take out if ($joke == null) return false; and else if($username == null) return false;. But when I put these statements into the PHP code, it seems that validate returns false. This is weird because $username and $joke will go to my database when I take out these statements meaning they cannot be null!.
Help is appreciated. Thanks.
Your validate function needs to have access to the $joke and $username objects.
function validate($joke, $validate) {
if ($joke == null)
return false;
else if ($username == null)
return false;
return true;
}
You can also get access to these variables by using the following inside your validate method:
global $joke, $username
However, it is better to declare what you're validating rather than relying on those variables being declared and set elsewhere in your code. Using global might fail silently for other reasons.
Variables have function scope. The variables $joke and $username do not exist inside the function, because you have neither declared nor passed them into the function. Use function parameters:
function validate($joke, $username) {
...
}
if (validate($joke, $username)) {
...
}
function validate($joke,$username)
also, filter those postvars before inserting them into your db.

Prepared statement not letting me call $mysqli->stmt_init()

I have done this before but am quite new to mysqli and prepared statements (as I'm sure you can see from this issue).
Where am I going wrong?
here is my connection function (part of the 'Connect' class)
public function site_db()
{
// Connect to MySQL
$link = mysqli_connect(SITE_HOST, SITE_ID, SITE_PW, SITE_DB);
// Check for Errors
if(mysqli_connect_errno())
{
//echo mysqli_connect_error(); //shouldnt show client specific error information.
die('Error connecting to mysql database please report.');
}
}
Heres the function which is causing the error:
public function exists ($what, $who)
{
$query = "SELECT * FROM users WHERE ? = ?";
// Get instance of statement
$stmt = $mysqli->stmt_init();
// Prepare query
if($stmt->prepare($query))
{
// Bind Parameters
$stmt->bind_param("ss", $what, $who);
// Execute statement
$stmt->execute();
// Bind result variables
$stmt->bind_result($result);
// Fetch Value
$stmt->fetch();
// catch num_rows result as variable
$username_result = $result->num_rows;
// Close Statement
$stmt->close();
}
if ($username_result != 0)
{
return true;
echo 'true';
}
else
{
return false;
echo 'false';
}
}
the error I get:
PHP Fatal error: Call to a member function stmt_init() on a non-object in somefile.php on line X
It is referring to the line:
$stmt = $mysqli->stmt_init();
am I making a stupid error here? Howcome I can't call that?
EDIT//
NOTE: I didn't make this very clear, but these two functions are within different classes.
public function site_db()
{
// Connect to MySQL
$mysqli = mysqli_connect(SITE_HOST, SITE_ID, SITE_PW, SITE_DB);
// Check for Errors
if(mysqli_connect_errno())
{
//echo mysqli_connect_error(); //shouldnt show client specific error information.
die('Error connecting to mysql database please report.');
}
return $mysqli;
}
public function exists (Mysqli $mysqli, $what, $who)
{
$query = "SELECT * FROM users WHERE ? = ?";
// Get instance of statement
$stmt = $mysqli->stmt_init();
// Prepare query
if($stmt->prepare($query))
{
// Bind Parameters
$stmt->bind_param("ss", $what, $who);
// Execute statement
$stmt->execute();
// Bind result variables
$stmt->bind_result($result);
// Fetch Value
$stmt->fetch();
// catch num_rows result as variable
$username_result = $result->num_rows;
// Close Statement
$stmt->close();
}
if ($username_result != 0)
{
return true;
echo 'true';
}
else
{
return false;
echo 'false';
}
}
How to use:
Instantiate first class that have site_db() method
$db = new Class();
Then instantiate second class that have exist() method
$query = new Class();
Then simply
$query->exist($db->site_db(), $what, $who );
it's because your $mysqli is not declared inside function exists(). Try a global $mysqli inside function exists() if your $mysqli is declared outside the function.
Or, probably better - make $mysql an new object inside your Connect class:
$this->mysqli = mysqli_connect(SITE_HOST, SITE_ID, SITE_PW, SITE_DB);
and in your function exists()
$stmt = $this->mysqli->stmt_init();

Categories