"Undefined Variable" notice - php

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.

Related

linking my database to my server on xampp for the first time [duplicate]

I'm working on streamlining a bit our db helpers and utilities and I see that each of our functions such as for example findAllUsers(){....} or findCustomerById($id) {...} have their own connection details for example :
function findAllUsers() {
$srv = 'xx.xx.xx.xx';
$usr = 'username';
$pwd = 'password';
$db = 'database';
$port = 3306;
$con = new mysqli($srv, $usr, $pwd, $db, $port);
if ($con->connect_error) {
die("Connection to DB failed: " . $con->connect_error);
} else {
sql = "SELECT * FROM customers..."
.....
.....
}
}
and so on for each helper/function. SO I thought about using a function that returns the connection object such as :
function dbConnection ($env = null) {
$srv = 'xx.xx.xx.xx';
$usr = 'username';
$pwd = 'password';
$db = 'database';
$port = 3306;
$con = new mysqli($srv, $usr, $pwd, $db, $port);
if ($con->connect_error) {
return false;
} else {
return $con;
}
}
Then I could just do
function findAllUsers() {
$con = dbConnection();
if ($con === false) {
echo "db connection error";
} else {
$sql = "SELECT ....
...
}
Is there any advantages at using a function like this compared to a Class system such as $con = new dbConnection() ?
You should open the connection only once. Once you realize that you only need to open the connection once, your function dbConnection becomes useless. You can instantiate the mysqli class at the start of your script and then pass it as an argument to all your functions/classes.
The connection is always the same three lines:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli($srv, $usr, $pwd, $db, $port);
$con->set_charset('utf8mb4');
Then simply pass it as an argument and do not perform any more checks with if statements.
function findAllUsers(\mysqli $con) {
$sql = "SELECT ....";
$stmt = $con->prepare($sql);
/* ... */
}
It looks like your code was some sort of spaghetti code. I would therefore strongly recommend to rewrite it and use OOP with PSR-4.

Issue with mysqli in PHP Warning: mysqli_stmt_prepare() expects parameter 1

I have been looking at this code for a while and can't figure out where the problem is.
I am new to coding in general, but especially new to CRUD and SQL. I want to create a prepared statement here to use variables instead of exact values. I don't understand where the issue comes from
I have a Databasetools.php
<?php
class DatabaseTools
{
//private $user = $_SESSION['userId']; // these get called when the object gets created
//private $userEmail = $_SESSION['emailUser'];
public function __construct($Name)
{
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "supersecretpassword";
$dbPort = "3306";
$this->name = $Name;
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $this->name, $dbPort);
$stmt = mysqli_stmt_init($conn);
if(!$conn)
{
die("connection faild: ".mysqli_connect_error());
}
}
public function lookup($dBName, $Row, $Column)
{
//$sql = "SELECT ".$Column." FROM ".$dBName." WHERE ".$Row.";";
$sql = "SELECT ? FROM ? WHERE ?;";
if(!mysqli_stmt_prepare($stmt, $sql))
{
echo "False";
}
else
{
mysqli_stmt_bind_param($stmt, "sss", $column, $dBName, $Row);
mysqli_stmt_execute($stmt);
$result = mysli_stmt_get_result($stmt);
echo $result;
}
// try to connect to the database
}
public function setCell($Database, $Row, $Column)
{
}
public function disconnect($dBName)
{
}
public function echotest()
{
}
}
?>
And I am using a page to check if the code is working
<?php
require "Model/php/databaseTools.php";
$loginData = new databaseTools("loginsystem");
$loginData->lookup("loginsystem","*","*");
?>
Thanks so much if you could point me in the write direction.
Are you sure you have $stmt value in the lookup function?
Try to add it as one of the parameters, something like this:
public function lookup($dBName, $stmt, $Row, $Column)
and then call it also with $stmt parameter:
$loginData->lookup("loginsystem", <stmt> ,"*","*");

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

'cannot access empty property' error in php

I am confused where i made mistake in my php code below. Although, i looked numerous time on my code but couldn't find why i am getting this error 'cannot access empty property' .
class DBTest{
//declare variables
private $servername = "localhost";
private $username = "root";
private $password = "";
private $database = "avn_test";
private static $conn;
private $results;
//constructor
public function __construct(){
self::$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();}
} //close constructor
public function executeQuery($query='') {
if(!empty($query)){
$query = self::$conn->real_escape_string($query);
Error on this line:
$this->results = self::$conn->query($query) or die("Error in database
connection".self::$conn->$error);
if( $this->results->num_rows > 0 ) {
$rowqry = array();
while($row = $this->results->fetch_object()) {
$rowqry[]= $row; } //close of while
$rarray['returnvar'] = $rowqry;
return $rarray;
} else {
return false; } // close of else
}//close of top if
else
return false;
} //close of function
function __destruct(){
self::$conn->close();}
} //close of class
//create an object of class DBTest
$test = new DBTest();
$q= "select * from test";
$tmp = $test->executeQuery($q);
if($tmp){
foreach($tmp as $key => $value){
echo $value;}
}
else
echo 'tmp var is empty';
In this line:
$this->results = self::$conn->query($query) or die("Error in database connection".self::$conn->$error);
Replace self::$conn->$error with self::$conn->error.
The $ is required when accessing a static property, but not needed for instance properties.
No need of $ in $conn function
self::$conn replace with self::conn
^^^^^^

Function returns boolean not string

What I want is to return MYSQL query in a array however my code returns a bool(true).
Here is the code from code.php
require('model.php');
$id = $_POST['id'];
$password = $_POST['password'];
$user = new user();
$row = $user->check_user($id, $password);
var_dump($row);
Here is the code from model.php
class config {
public $dbhost = "localhost";
public $dbuser = "root";
public $dbpass = "";
public $dbused = "dbname";
function dbconn() {
$conn = mysqli_connect($this->dbhost,$this->dbuser,$this->dbpass,$this->dbused);
if(mysqli_connect_errno()) {
printf("Connection failed: " . mysqli_connect_error());
exit();
}
return $conn;
}
}
class user {
function check_user($id, $pass) {
$config = new config();
$conn = $config->dbconn();
$query = $conn->prepare("SELECT id, password, status FROM e_users WHERE id = ? AND password = ?");
$query->bind_param('is', $id, $pass);
try {
$query->execute();
return $query->fetch();
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
I think the problem is in the $query->fetch(); because I tried return 'test'; and it works fine. Even return an array works fine.
Can anyone help me?
As The Blue Dog pointed out, fetch() returns a status flag, not the row itself. But fetch_assoc() will return a row.
Have a look here:
http://php.net/manual/en/mysqli-stmt.fetch.php
If you work with fetch, you need to bind the variables:
$stmt->bind_result($mySelectedValue_1, $mySelectedValue_2);
Here are examples with fetch_assoc():
http://php.net/manual/de/mysqli.quickstart.prepared-statements.php
So this should work fine:
$row = $res->fetch_assoc();

Categories