My global variable isn't recognised within a function (PHP) - php

My programming level is fairly elementary so a 'coding for idiots' type of explanation would be great...
I have the following code:
<?php
$host = 'localhost';
$user = 'user';
$password = 'password';
$db_name = 'db_name';
$connect = mysqli_connect($host, $user, $password);
mysqli_select_db($connect, $db_name) or die ("Couldn't connect");
function roll_die() {
$throw = rand(1, 6);
return $throw;
}
function get_subtotal() {
$query = "SELECT * FROM throws";
$result = mysqli_query($connect, $query);
while ($row = $result->fetch_assoc()) {
echo $row['value']."<br>";
}
}
?>
I get an error because the '$connect' in the function subtotal() is apparently undefined. How can that be if it's defined at the top of the page? Wouldn't that make it a global function?
Please don't just give me the correct code to fix this. Could you explain what's going on and how PHP defines and stores variables?
Thanks!

Ok, I found the answer.
At the top of the page:
$connect = mysql_connect($host, $user, $password);
Then within the function:
global $connect;
Actually, I found the answer in another question which was essentially asking the same thing, so apologies for the repost.

Related

query function not work in php7

first of all, I want to thank you to everyone who gives this post attention. I got a problem when migrating code from php5 to php7. I actually don't know what is going wrong in my code
class database {
public function __construct () {
$conn = mysqli_connect("localhost", "root", "");
mysqli_select_db($conn, 'crm');
}
public function view_chart(){
$data = mysqli_query($conn, "select * from t_chart");
while($d = mysqli_fetch_array($data)){
$hasil[] = $d;
}
return $hasil;
}
foreach($db->view_chart() as $x){
echo "<option value='$x[id_chart_cat]'>$x[chart_name]</option>";
}
the view_chart() not work but it's work in php4 as well. anyone here can tell me what is going wrong with this code? I really appreciate any answer which is related to this question. Thank you.
You have to declare $conn as class member variable so it's accessible from other class functions.
Do:
class database {
public $conn; // added
public function __construct () {
$this->conn = mysqli_connect("localhost", "root", ""); // modified
mysqli_select_db($this->conn, 'crm'); // modified
}
public function view_chart(){
$data = mysqli_query($this->conn, "select * from t_chart"); // modified
while($d = mysqli_fetch_array($data)){
$hasil[] = $d;
}
return $hasil;
}
foreach($db->view_chart() as $x){
echo "<option value='$x[id_chart_cat]'>$x[chart_name]</option>";
}
when I updated my PHP-scripts to PHP7 I had issues with
mysqli_fetch_array()
you should replace it with a function like
mysqli_fetch_assoc()
did you first check and make sure your connection was being made? and how i always did it in 7 was like this
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbName = "test";
$conn = new mysqli($servername, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
then you can do
<?php
$query = "SELECT * FROM whatever";
$result = $conn->query($query);
$hasil = [];
?>
then you should be able to just do
while($row = $result->fetch_assoc()){
$hasil[] = $row;
}
return $hasil;
then go into your foreach...not sure if that's what your looking for but hope it helps

Can't connect on database on my localhost [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 8 years ago.
Improve this question
I have php script:
<?php
$host = $_GET['host'];
$username = $_GET['username'];
$pass = $_GET['pass'];
$con = mysql_connect($host, $username, $pass);
if (!$con) {
echo 'Connection failed!';
} else {
echo 'Connected successfully!';
}
mysql_close($con);
?>
running on remote server and when I execute it and try to connect to database located on my PC i get an error:
Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on '109.60.110.255' (4) in /home/a6859995/public_html/zavrsni/connect.php on line 12
How can I fix that?
I recommend to use pdo like this:
class_config.php:
class class_config {
public static $db_host = 'localhost';
public static $db_name = 'yourdbname';
public static $db_user = 'youruser';
public static $db_pass = 'yourpass';
}
class_pdo.php:
require_once "class_config.php";
class class_pdo {
public static function dbFactory() {
$host = class_config::$db_host;
if(strpos($host,":") !==false) {
$parts = explode(":",$host);
$hostname = "unix_socket=".$parts[1];
} else {
$hostname = "host=$host";
}
$user = class_config::$db_user;
$pass = class_config::$db_pass;
$dbase = class_config::$db_name;
$pdo = new PDO("mysql:$hostname;dbname=$dbase", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
}
}
use it in your script like this:
require_once("class_pdo.php");
$pdo = class_pdo::dbFactory();
$stmt = $pdo->prepare("SELECT * FROM `tablename` WHERE id = :id ");
$stmt->bindValue(":id", $id, PDO::PARAM_INT);
$stmt->execute();
[...]
Try This instead: mysql_connect() is deprecated so use mysqli_connect...
$host = $_GET['host'];
$username = $_GET['username'];
$pass = $_GET['pass'];
$databae = $_GET['database'];
$con = mysqli_connect($host, $username, $pass, $database);
if (mysqli_connect_errno()) {
echo 'Connection failed!';
} else {
echo 'Connected successfully!';
}
mysql_close($con);
?>
Though mysql_connect() is deprecated try using PDO.. I am just presenting it in mysql_connect for you..
$host = $_GET['host'];
$username = $_GET['username'];
$pass = $_GET['pass'];
$database = $_GET['database'];
$connect=new connect($host,$username,$pass,$database);
class connect{
function __construct($host,$user,$password,$db_name){
mysql_connect($host,$user,$password) or die("Connection error");
mysql_select_db($db_name);
$error=mysql_error();
if (!empty($error))
{
echo $error;
}
}
}
Thanks everyone on help. Main problem were privileges on MySQL database, but PDO usage helped me to understand how it's to be done these days, sorry on n00b code at start :D

Fatal error: Call to a member function query() on a non object

I've got this error:
Fatal error: Call to a member function query() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/login.php on line 8
The line is this:
$res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");
This is login.php:
$user = $_POST['user'];
$pass = $_POST['pass'];
$pw = md5($pass);
include_once('connect.php');
function check_login($user,$pw,&$result){
$res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");
$cont = 0;
while($row = $res->fetch_object()){
$cont++;
$result = $row;
}
if($cont == 1){
return 1;
}
else{
return 0;
}
}
if(!isset($_SESSION['userid'])){
if(isset($_POST['login'])){
if(check_login($user,$pw,$result) == 1){
session_start();
$_SESSION['userid'] = $result->id_user;
header("location:index.php?var=ok");
}
else{
header('location:index.php?var=log');
}
}
}
And the code of connect.php :
$mysqli = new mysqli('localhost', 'root', 'pass', 'cms' );
if ($mysqli->connect_error) {
die('Error de Conexión (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
What could be the problem? Problems connecting the database?
This is most likely a scoping issue. This means that the variable $mysqli that you define in your included file is outside of the check_login function's scope (i.e. is not known inside this function).
You could try to get the $mysqli variable from global scope with
function check_login($user,$pw,&$result){
global $mysqli;
$res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");
// ...
Edit: Oh, and you should also mind the SQL injection vulnerabiliy in your code. Use prepared statements to prevent this issue (or at least escape your input variables with a function like mysqli::real_escape_string).
function check_login($user,$pw,&$result){
global $mysqli;
$res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");
$cont = 0;
while($row = $re[...]
Mind the "global". This puts the var in the scope of your method.
This is a quick and dirty solution, but will work in this case.
It looks like your $mysqli variable is not being set properly within the scope of your code thats executing the query. Can you confirm that $mysqli is indeed a mysqli object and not, say, set to null?
You can check this by doing: echo print_r($mysqli); right before you call the ->query method in your code.
If it is not set properly, track the variable backward in your code until you see why
variable $mysqli in function check_login is out of scope (it is declare outside the function) so it is null.
public function connectDB($DBServer, $DBUser, $DBPass, $DBName) {
global $con;
$con = new mysqli($DBServer, $DBUser, $DBPass, $DBName) or die ("Error occured");
return $con;
and then pass $con in all the functions that you define or run wherever.

Functions, SQL Connects and Global Variable

Is there anything wrong with connecting and closing to a database by calling the function below with the mysql_query and mysql_fetch_array commands between the two
<?php
function dbconnect()
{
$sql = "localhost";
$username = "------";
$password = "-----";
$connection = mysql_connect($sql, $username, $password) or
die("unwable to cct");
$databse = mysql_select_db("-------", $connection);
global $connection;
}
function close()
{
global $connection;
mysql_close($connection);
}
dbconnect();
$query = "Some SQL Statement";
$data = mysql_query($query, $connection); - L1
while (mysql_fetch_assoc($data))
{
//echo something
}
close();
?>
At present, I am getting an error saying that $connection at L1 needs to be a resource but is a BOOL. If I give a die statement there, the same is triggered. I have no idea what is wrong. Please spot any errors you can. I have to take a sabbatical from coding and I am back after a while.
Thanks & regards
You must use the global keyword before assigning the $connection variable. Otherwise, you declare a local $connection inside the function and then call a reference to the yet non-existent global $connection. In the other functions, that non-existent global is used.
function dbconnect()
{
// Global first to be sure the subsequent $connection is the global
// rather than a new one local to this function
global $connection;
$sql = "localhost";
$username = "------";
$password = "-----";
// Now this modifies the global $connection
$connection = mysql_connect($sql, $username, $password) or die("unwable to cct");
$databse = mysql_select_db("-------", $connection);
}
More readable would be to use the $GLOBALS array:
function dbconnect()
{
$sql = "localhost";
$username = "------";
$password = "-----";
// Using the $GLOBALS superglobal array
$GLOBALS['connection'] = mysql_connect($sql, $username, $password) or die("unwable to cct");
$databse = mysql_select_db("-------", $GLOBALS['connection']);
}
Best of all would be to return $connection from dbconnect() and use that value in other functions:
function dbconnect()
{
$sql = "localhost";
$username = "------";
$password = "-----";
$connection = mysql_connect($sql, $username, $password) or
die("unwable to cct");
$databse = mysql_select_db("-------", $connection);
// Return from the function
return $connection;
}
// call as
$connection = dbconnect();
// and define your other functions to accept $connection as a parameter
declare global $connection before calling mysql_connect()
function dbconnect()
{
global $connection;
$sql = "localhost";
$username = "------";
$password = "-----";
$connection = mysql_connect($sql, $username, $password) or
die("unwable to cct");
$databse = mysql_select_db("-------", $connection);
}
Not too sure but try closing it by using
mysql_Close($Connection);
everything else looks good
Just put the global $connection; line in the beginning of the function instead and it should work. Using global keyword at the end of the function implies that you want to use the global variable $connection. But the thing you will be doing now is, assingning global variable $connection "the actual connection resourceID".

"Undefined Variable" notice

Im new to php so im sure this is an easy one. Im getting this error
Notice: Undefined variable: conn in C:\Dev\Webserver\Apache2.2\htdocs\EclipsePHP\thecock\php\db.php on line 23
for this code
<?php
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
$conn = new mysqli($host, $username, $password, $database);
if (! $conn) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}else{
echo("all ok!");
}
function getContent($id) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) { # line 23
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
?>
How do I fix the notice?
Change your function to:
function getContent($id, $conn) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
You don't declare the "original" $conn in the scope of the function. Inside the function you only have access to variables declared inside the function or provided via parameters.
Another way would be to declare the variable as global in your function:
function getContent($id) {
global $conn;
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
But you should only do this, if there is no other way. Globals make it hard to debug and maintain the code.
See also Variable scope and why global variables are bad.
Edit:
Yes e.g. you can have a DB class:
class DB {
private static $conn = null;
public static function getConnection() {
if (is_null(DB::$conn)) {
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
DB::$conn = new mysqli($host, $username, $password, $database);
}
return DB::$conn;
}
}
Of course this is not the best implementation ;) But it should give you the right idea. Then you can get the the connection:
DB::getConnection()
conn is a global variable. To access it within a function:
function getContent($id) {
global $conn;
...
}
Otherwise the function can't see it.

Categories