This question already has answers here:
Giving my function access to outside variable
(6 answers)
Closed 6 years ago.
// db.php
$db = array();
$db['host'] = '127.0.0.1';
$db['login'] = 'root';
$db['pass'] = '';
$db['name'] = 'edziennik';
$db_conn = new PDO('mysql:host='.$db['host'].';dbname='.$db['name'].';charset=utf8mb4', $db['login'], $db['pass']);
login_system.php
<?php
require_once('cfg/db.php');
function validate_data($l, $p)
{
$query = "SELECT * FROM e_users WHERE login='"+$l+"' AND password='"+$p+"'";
$stmt = $db_conn->query($query);
$row_count = $stmt->rowCount();
if($row_count===1)
return true;
else
return false;
return false;
}
Error: Call to a member function query() on null
Adding global prefix don't helped.
I lost lot of time to fix it, so i ask you.
$db_conn doesn't exist in the validate_data scope. Pass it in as an argument.
<?php
require_once('cfg/db.php');
function validate_data($db_conn, $l, $p)
{
$query = "SELECT * FROM e_users WHERE login='".$l."' AND password='".$p."'";
$stmt = $db_conn->query($query);
$row_count = $stmt->rowCount();
if($row_count===1)
return true;
else
return false;
return false;
}
And when you call it, pass in the connection.
$check = validate_data($db_conn, $whateverLIs, $whateverPIs);
Edit: -Fixed concat operator as noted by #Bamar.
Related
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 2 years ago.
I receive this error:
Fatal error: Call to a member function fetch() on boolean in
C:\xampp\htdocs\repo\generator\model\database.php on line 34
When I run this code:
class database
{
private $user = 'root';
private $pass = '';
public $pdo;
public function connect() {
try {
$this->pdo = new PDO('mysql:host=localhost; dbname=generatordatabase', $this->user, $this->pass);
echo 'Połączenie nawiązane!';
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone: ' . $e->getMessage();
}
}
public function createTable() {
$q = $this->pdo -> query('SELECT * FROM article');
while($row = $q->fetch()) {
echo $row['id'].' ';
}
$q->closeCursor();
}
}
?>
As per the PHP manual for PDO::query
PDO::query() returns a PDOStatement object, or FALSE on failure.
It looks like your query is failing (on line 33) and thus returning a BOOLEAN (false), likely because at that point in execution, PDO has not connected to a database that contains a table called article. In the connect() method I see that it tries to connect to a db called 'generatordatabase'; ensure this connection is being made prior to calling createTable(), otherwise ensure that it contains a table called 'article'.
I would recommend adding some more code examples, for instance the code that calls this class/method before the error is triggered.
Some error handling will help you avoid issues like this:
$q = $this->pdo->query('SELECT * FROM article');
//error case
if(!$q)
{
die("Execute query error, because: ". print_r($this->pdo->errorInfo(),true) );
}
//success case
else{
//continue flow
}
I'm not sure wheatear this is exactly the error I struggled with, but my error was due to my $con variable, I used a single $con for 2 SQL statements, for example:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con->prepare($sql1);
if ($stm1->execute()) {
I should have done:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$con1 = new mysqli($host,$username,$password,$database);
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con1->prepare($sql1);
$stm1->execute()
This question already has answers here:
PHP global in functions
(7 answers)
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 3 years ago.
I was just organizing one of my codes and notice that leaving the connect-mydb.php out of a function, it doesnt work.
I always thought the include would be loaded prior to any of the functions.
connect-mydb.php
<?php
$server = 'localhost';
$user = 'myuser';
$pass = 'mypass';
$db = 'mydb';
$mysqli = new mysqli($server, $user, $pass, $db);
?>
testdb_out.php (doesnt work)
<?php
include 'connect-mydb.php';
function UpdateDB() {
echo "working\n";
$query = "UPDATE mytable SET myfield = 'aloha' WHERE id = '1'";
$saved = mysqli_query($mysqli, $query);
if ($saved) {
echo 'success';
}else{
echo 'failed';
}
}
UpdateDB();
?>
testdb_within.php (works)
<?php
function UpdateDB() {
include 'connect-mydb.php';
$query = "UPDATE mytable SET myfield = 'aloha' WHERE id = '1'";
$saved = mysqli_query($mysqli, $query);
if ($saved) {
echo 'success';
}else{
echo 'failed';
}
}
UpdateDB();
?>
In testdb_out, shouldnt the include be loaded prior to the function? That works in other programming languages.
So I am attempting to use MySQLi, however, I keep getting thrown the error
Fatal error: Call to a member function query() on null in
/home/u740966689/public_html/dashboard/API/infFunctions.php on line 78
I'm unsure why this is... I read up on some other questions and changed a few things such as how I connect to the database but I still get the error.
MY CODE:
File 1:
require 'infFunctions.php';
$DatabaseHost = '***';
$DatabaseUser = '***';
$DatabasePass = '***';
$DatabaseName = '***';
$mysqli = new mysqli("$DatabaseHost","$DatabaseUser","$DatabasePass","u740966689_site") or die ("infAPI | Could not connect to the database");
if (isset($_GET['Type'])){
$Type = $_GET['Type'];
if ($Type == 'Register') {
$Response = Signup($_GET['name'],$_GET['password'],$_GET['email']);
if ($Response == '1') {
$resp = 'success';
} else if ($Response == '2') {
$resp = 'error_one';
} else if ($Response == '3') {
$resp = 'error_two';
} else {
$resp = 'error_three';
}
echo $resp;
}
}
file 2:
function Signup($Username, $Password, $Email){
$UserArray = $mysqli->query("SELECT * FROM infWebAccounts WHERE Username='$Username'");
$UserArray2 = $mysqli->query("SELECT * FROM infPendingAccounts WHERE Username='$Username'");
if (mysqli_num_rows($UserArray) == 0 AND mysqli_num_rows($UserArray2) == 0){
$Password = hash("sha512",$Password);
$Query = $mysqli->query("INSERT INTO infPendingAccounts (Username,Password,Email,Verified) VALUES ('$Username','$Password','$Email',N')");
return '1';
}elseif (mysqli_num_rows($UserArray) > 0 ){
return '2';
}else{
return '3';
}
}
The $mysqli object is created in the global scope but you're trying to use it inside a function. This is in violation of PHP's scoping rules, where a child scope can't implicitly access state in a parent scope.
PHP Scoping Rules
You can work around it by either using global to explicitly indicate that you want to access a variable in the global scope (which is generally a bad idea and should be avoided as it can lead to spaghetti code), or add a parameter to your function that will allow you to pass the mysqli object in.
If you want to use a global variable you have to add this to the function.
Easily add global $mysqli; at the beginning of the Signup()-function
function Signup($Username, $Password, $Email)
{
global $mysqli;
$UserArray = $mysqli->query("SELECT * FROM infWebAccounts WHERE Username='$Username'");
$UserArray2 = $mysqli->query("SELECT * FROM infPendingAccounts WHERE Username='$Username'");
.
.
.
Check out PHP: Variable scope
In PHP global variables must be declared global inside a function if they are going to be used in that function.
The problem is with PHP variable scoping. Add global $mysqli inside Signup() function before you refer to the $mysqli variable:
function Signup($Username, $Password, $Email){
global $mysqli; // Add this line
$UserArray = $mysqli->query("SELECT * FROM infWebAccounts WHERE Username='$Username'");
$UserArray2 = $mysqli->query("SELECT * FROM infPendingAccounts WHERE Username='$Username'");
if (mysqli_num_rows($UserArray) == 0 AND mysqli_num_rows($UserArray2) == 0){
$Password = hash("sha512",$Password);
$Query = $mysqli->query("INSERT INTO infPendingAccounts (Username,Password,Email,Verified) VALUES ('$Username','$Password','$Email',N')");
// $rTech = new Roblox();
// $rTech -> DoLogin($rTech->password);
// $rTech -> SendPM($rTech->GetUserID($Username),"RDS Owner Analytics Site Verification","Please goto the site and verify with : \n" . hash("sha512",$Username.$Password));
return '1';
}elseif (mysqli_num_rows($UserArray) > 0 ){
return '2';
}else{
return '3';
}
}
or you can simply pass your connection variable as parameter in your SignUp function
function Signup($Username, $Password, $Email, $mysqli){
}
Learn more about variable scoping here: http://php.net/manual/en/language.variables.scope.php
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 2 years ago.
I receive this error:
Fatal error: Call to a member function fetch() on boolean in
C:\xampp\htdocs\repo\generator\model\database.php on line 34
When I run this code:
class database
{
private $user = 'root';
private $pass = '';
public $pdo;
public function connect() {
try {
$this->pdo = new PDO('mysql:host=localhost; dbname=generatordatabase', $this->user, $this->pass);
echo 'Połączenie nawiązane!';
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone: ' . $e->getMessage();
}
}
public function createTable() {
$q = $this->pdo -> query('SELECT * FROM article');
while($row = $q->fetch()) {
echo $row['id'].' ';
}
$q->closeCursor();
}
}
?>
As per the PHP manual for PDO::query
PDO::query() returns a PDOStatement object, or FALSE on failure.
It looks like your query is failing (on line 33) and thus returning a BOOLEAN (false), likely because at that point in execution, PDO has not connected to a database that contains a table called article. In the connect() method I see that it tries to connect to a db called 'generatordatabase'; ensure this connection is being made prior to calling createTable(), otherwise ensure that it contains a table called 'article'.
I would recommend adding some more code examples, for instance the code that calls this class/method before the error is triggered.
Some error handling will help you avoid issues like this:
$q = $this->pdo->query('SELECT * FROM article');
//error case
if(!$q)
{
die("Execute query error, because: ". print_r($this->pdo->errorInfo(),true) );
}
//success case
else{
//continue flow
}
I'm not sure wheatear this is exactly the error I struggled with, but my error was due to my $con variable, I used a single $con for 2 SQL statements, for example:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con->prepare($sql1);
if ($stm1->execute()) {
I should have done:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$con1 = new mysqli($host,$username,$password,$database);
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con1->prepare($sql1);
$stm1->execute()
This question already has answers here:
Call to undefined method mysqli_stmt::get_result
(10 answers)
Closed 11 months ago.
I'm quite new to prepared statements and am not sure I am doing this right.
Here is what I try:
$currgame = 310791;
$sql = "SELECT fk_player_id, player_tiles, player_draws, player_turn, player_passes, swapped FROM ".$prefix."_gameplayer WHERE fk_game_id = ?";
$stmt = $mysqli->stmt_init();
$data = array();
if($stmt->prepare($sql)){
$stmt->bind_param('i', $currgame);
$stmt->execute();
$fk_player_id = null; $player_tiles = null; $player_draws = null; $player_turn = null; $player_passes = null; $swapped = null;
$stmt->bind_result($fk_player_id, $player_tiles, $player_draws, $player_turn, $player_passes, $swapped);
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()){
$data[] = $row;
}
$stmt->close();
}
// to display own games
foreach ($data as $row) {
if ($row['fk_player_id'] == $playerid) {
$udraws = $row['player_draws']+1;
$upass = $row['player_passes'];
$uswaps = $row['swapped'];
echo 'uDraws: '.$udraws.'<br>';
echo 'uPass: '.$upass.'<br>';
echo 'uSwaps: '.$uswaps.'<br><br>';
}
}
// to display other games
foreach ($data as $row) {
if ($row['fk_player_id'] != $playerid) {
$opponent = $row['fk_player_id'];
$oppTiles = $row['player_tiles'];
$odraws = $row['player_draws']+1;
$opass = $row['player_passes'];
$oswaps = $row['swapped'];
echo 'oID: '.$opponent.'<br>';
echo 'oTiles: '.$oppTiles.'<br>';
echo 'oDraws: '.$odraws.'<br>';
echo 'oPass: '.$opass.'<br>';
echo 'oSwaps: '.$oswaps.'<br><br>';
}
}
I get an "ServerError" when trying to run this: It is the $res = $stmt->get_result(); that makes the error, but not sure why.
PHP Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/mypage/public_html/TEST/preparedstatement.php on line 61
Depending on your PHP/MySQL setup you may not be able to use get_result().
The way to get around this is to bind the results.
For example:
$stmt->execute();
$fk_player_id = null; $player_tiles = null; $player_draws = null; $player_turn = null; $player_passes = null; $swapped = null;
$stmt->bind_result($fk_player_id, $player_tiles, $player_draws, $player_turn, $player_passes, $swapped);
while ($stmt->fetch()) { // For each row
/* You can then use the variables declared above, which will have the
new values from the query every time $stmt->execute() is ran.*/
}
For more information click here
Since I don't see it in your code, make sure you're instantiating the mysqli object before trying to query on it:
$mysqli = new mysqli("127.0.0.1", "user", "password", "mydb");
if($mysqli->connect_error){
die("$mysqli->connect_errno: $mysqli->connect_error");
}
Also, a ServerError would certainly show up in your logs and point you in the right direction.
while (mysqli_stmt_fetch($stmt)) {
printf ("%s (%s)\n", $name, $code);
}
This might help you:
http://php.net/manual/en/mysqli-stmt.fetch.php