PHP and MySQL. Include Connect-DB out of a function [duplicate] - php

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.

Related

PHP insert function not working [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
I'm trying to make some insert function, but something is wrong, and can find where is the problem. Basically o just set some informations, and this same should be insert in database. The message errors are:
Notice: Undefined variable: conn in /Applications/AMPPS/www/teste/index.php on line 21
Fatal error: Call to a member function query() on a non-object in /Applications/AMPPS/www/teste/index.php on line 21
ini_set('display_errors',1);
ini_set('display_startup_erros',1);
error_reporting(E_ALL);
$dbtype = "mysql";
$dbhost = "XXXXXXXXXX";
$dbname = "XXXXXXXXXX";
$dbuser = "XXXXXXXXXX";
$dbpass = "XXXXXXXXXX";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
function Insertdata($table,$field,$data){
$field_values= implode(',',$field);
$data_values=implode(',',$data);
$sql = "INSERT into". " ".$table." ".$field_values. "VALUES(".$data_values.")";
$result = $conn->query($sql);
}
$table="teste";
$field_values=array("nome","idade","email","cidade");
$data_values=array("Teste","14","teste#yahoo.com","Rio de Janeiro");
$sample = Insertdata($table,$field_values,$data_values);
if($result)
{
echo "inserted";
}
else
{
echo "not inserted";
}
You didn't pass $conn to your function, you'll need to do that in order to have it in scope:
function Insertdata($table, $field, $data, $conn){
$field_values= implode(',',$field);
$data_values=implode(',',$data);
$sql = "INSERT into". " ".$table." ".$field_values. "VALUES(".$data_values.")";
$result = $conn->query($sql);
}

mysqli Call to member function() error

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

php pdo Call to a member function query() on null [duplicate]

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.

"No database selected" error with mysql_query [duplicate]

This question already has answers here:
MYSQL PHP No Database Selected - Can't Find Error
(2 answers)
Closed 7 years ago.
Here is my php code
<?php
error_reporting(E_ALL);
class ll{
function ll(){
include "sql.php";
}
function getUser($ID) {
$sql="select * FROM users where ID=$ID";
$res = mysql_query($sql) or die (mysql_error());
$obj = mysql_fetch_object($res);
return $obj;
}
function setOfflineALL() {
$sql="update users set online=0";
mysql_query($sql);
}
}
$services = new ll();
$services->setOfflineALL(); // THIS WORKS !
$services->getUser(1); // THIS GIVES error: No database selected
?>
and sql.php is:
<?php $hostname_con1 = "localhost";
$database_con1 = "db1";
$username_con1 = "root";
$password_con1 = "mypass";
$con1 = mysql_connect($hostname_con1, $username_con1, $password_con1) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_con1);
mysql_set_charset('utf8',$con1);
?>
sql.php is correct (no error)
setOfflineALL works fine (no error)
getUser raises "no database selected error !", however I do select one with mysql_select_db
I do use php5.4
Any clue ?
I also tried:
function getUser($ID) {
$hostname_con1 = "localhost";
$database_con1 = "db1";
$username_con1 = "root";
$password_con1 = "mypass";
$con1 = mysql_connect($hostname_con1, $username_con1, $password_con1) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_con1);
mysql_set_charset('utf8',$con1);
$sql="select * FROM users where ID=$ID";
$res = mysql_query($sql) or die (mysql_error());
$obj = mysql_fetch_object($res);
return $obj;
}
And still have error:
No database selected
You should try this:
mysql_select_db($database_con1, $con1);
And you should give your database variable to your query too:
mysql_query("query", $con1);
And I strongly advise you not to use mysql but use PDO or mysqli
PDO
Mysqli

Call to a member function query() only on localhost [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 8 years ago.
I'm getting this error only when I try connect to my localhost, but if i test on my web host, everything is running perfect.
The error i get is pointing on my $query = $dbh->query("SELECT * FROM video");
<?php
$query = $dbh->query("SELECT video_img FROM video");
while($r = $query->fetch(PDO::FETCH_OBJ)) {
echo $r->video_title;
}
?>
db connection
<?php
$user = "root";
$pass = "";
try {
$dbh = new PDO('mysql:host=localhost;dbname=streaming', $user, $pass);
foreach($dbh->query('SELECT * from video') as $row) {
//print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Any tips :)?
Thanks
Looking at the codes you posted, $dbh doesn't make sense since no PDO connection has be initialized:
Second, you are selecting column video_img, then accessing/fetching $r->video_title. This doesn't make sense also:
$dbh = new PDO('mysql:host=localhost;dbname=DATABASE_NAME', 'username', 'password');
$query = $dbh->query("SELECT video_img FROM video");
while($r = $query->fetch(PDO::FETCH_OBJ)) {
echo $r->video_img;
}

Categories