PHP undefined variable mysqli connection - php

I have a mysql connection which is included in a separate file:
require 'settings.php';
and I have a file with all functions, also included:
require 'functions.php';
In the settings there it looks like this:
$db = mysqli_connect("host", "username", "passwort", "database");
if(!$db) {
exit("Error: ".mysqli_connect_error());
}
and a function uses this connection like this:
function includehomepage() {
$data = array();
$query = "SELECT pagecontent FROM `pages` WHERE `id` = `0`";
$query = mysqli_query($db, $query);
$data = mysqli_fetch_assoc($query);
return $data['pagecontent'];
}
But I get an error message like this:
Undefined variable: db in /var/... on line 18
Do you have an answer? The variable have to be defined in the included file.. I am confused. Thanks for your answers!

Variable scope problem. Look at global
function includehomepage() {
global $db;
$data = array();
$query = "SELECT pagecontent FROM `pages` WHERE `id` = '0'";
$query = mysqli_query($db, $query);
$data = mysqli_fetch_assoc($query);
return $data['pagecontent'];
}

$db is a global variable to includehomepage function. If you want to access it, then you have to pass it to the function or declare it as global inside the function.
like
function includehomepage() {
global $db;
$data = array();
$query = "SELECT pagecontent FROM `pages` WHERE `id` = '0'";
$query = mysqli_query($db, $query);
$data = mysqli_fetch_assoc($query);
return $data['pagecontent'];
}
or have it as a parameter in your function and pass it via call.
function includehomepage($db) {
$data = array();
$query = "SELECT pagecontent FROM `pages` WHERE `id` = '0'";
$query = mysqli_query($db, $query);
$data = mysqli_fetch_assoc($query);
return $data['pagecontent'];
}
includehomepage($db);

Related

PHP script not working as expected

My php script is woking outside function but not inside function.
$uid = $_SESSION['user_id'];
function getUserName($conn) {
$sql = "SELECT * FROM `tbl_user` WHERE `user_id` ='".$uid."' ";
$row = $conn->query($sql)->fetch_array();
return $row["user_name"];
}
Unable to get it where I am wrong.
DO NOT use global variable. It's evil.
Pass the user ID as parameter to the function:
function getUserName($conn, $uid) {
$sql = "SELECT * FROM `tbl_user` WHERE `user_id` ='".$uid."' ";
$row = $conn->query($sql)->fetch_array();
return $row["user_name"];
}
echo getUserName($conn, $_SESSION['user_id']);
try this
function getUserName($uid, $conn) {
// code here
}
Best thing you can do is avoid globals and just pass the uid as a parameter:
$uid = $_SESSION['user_id'];
$username = getUserName($conn, $uid);
function getUserName($uid, $conn) {
$sql = "SELECT * FROM `tbl_user` WHERE `user_id` ='".$uid."' ";
$row = $conn->query($sql)->fetch_array();
return $row["user_name"];
}
Read http://php.net/manual/en/language.variables.scope.php to learn about variable scope in PHP
Also read this post about SQL injection
you need to call the function to work code inside funtion

how to make function to delete data from db

can any body tell me that how can i make function of this query in PHP that's why whenever i want it i just call a function to delete record. i am new in coding. please suggest simplest code to write function for this.
<?php
if (isset($_GET['delete']))
{
$query= "DELETE FROM student WHERE id='".$_GET['delete']."'";
global $db;
$row = $db->exec($query);
}
$query= "SELECT * FROM student";
global $db;
$statement = $db->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$result = $result;
?>
Try this:
if (isset($_GET['delete']))
{
deleteStudent($_GET['delete']);
}
$query= "SELECT * FROM student";
global $db;
$statement = $db->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$result = $result;
function deleteStudent($id) {
global $db;
$query= "DELETE FROM student WHERE id='".$id."'";
$row = $db->exec($query);
return $row; // expects it return the succes/failure flags properly.
} ?>

Variable is undefined inside a function, cannot reach MySQL $connection inside a function

I have a code that works when I use it on a page but Im trying to make this a function. I cant get it to work, it seems like the variables $customer and $system arent being sent through to the code. Even if I type it in Raw. Any idea whats wrong? $Customer is the name of the customer, $system can be 'Source' or 'Target'.
function status_total($customer, $system){
$sql_customer = "SELECT * FROM `Customer` WHERE Cust_Name = '$customer' LIMIT 0,1";
$customer_selection = mysqli_query($conn,$sql_customer);
$customer_row = mysqli_fetch_assoc($customer_selection);
$env_lines = $customer_row["Env_Lines"];
$cust_id = $customer_row["Cust_ID"];
$sql_last_records = "SELECT * FROM $system WHERE Cust_ID = $cust_id ORDER BY Time DESC LIMIT $env_lines";
$record_selection = mysqli_query($conn, $sql_last_records);
$result = mysqli_fetch_all($record_selection, MYSQLI_ASSOC);
$states = array_column($result, "Stat");
if($states == array_fill(0, count($states), "Run")) {
echo "Success";
} else
echo "Fail";
}
https://gist.github.com/R2D2-05/78d81566e4bf0eafd1fa
The problem with your code is $conn variable which is treated a local variable inside a function. You should:
function status_total($customer, $system){
global $conn;
$sql_customer = "SELECT * FROM `Customer` WHERE Cust_Name = '$customer' LIMIT 0,1";
$customer_selection = mysqli_query($conn,$sql_customer);
$customer_row = mysqli_fetch_assoc($customer_selection);
$env_lines = $customer_row["Env_Lines"];
$cust_id = $customer_row["Cust_ID"];
$sql_last_records = "SELECT * FROM $system WHERE Cust_ID = $cust_id ORDER BY Time DESC LIMIT $env_lines";
$record_selection = mysqli_query($conn, $sql_last_records);
$result = mysqli_fetch_all($record_selection, MYSQLI_ASSOC);
$states = array_column($result, "Stat");
if($states == array_fill(0, count($states), "Run")) {
echo "Success";
} else
echo "Fail";
}
Or you can also pass the $conn through the function, so change the function's definition to:
function status_total($conn, $customer, $system){...}

PHP Functions and MySQL Connectivity

I have a database.php file which stores the database connection info like this:
<?php
// Database connectivity stuff
$host = "localhost"; // Hostname for the database. Usually localhost
$username = "root"; // Username used to connect to the database
$password = "root"; // Password for the username used to connect to the database
$database = "blog"; // The database used
// Connect to the database using mysqli_connect
$connection = mysqli_connect($host, $username, $password, $database);
// Check the connection for errors
if (mysqli_connect_errno($connection)) {
// Stop the whole page from loading if errors occur
die("<br />Could not connect to the database. Please check the settings and try again.") . mysqli_connect_error() . mysqli_connect_errno();
}
?>
And also a functions.php file that has the following:
<?php
// Functions file for the system
function show_posts($user_id) {
$posts = array();
$sql = "SELECT body, stamp from posts where user_id = '$user_id' order by stamp desc";
$result = mysqli_query($connection, $sql);
}
function show_users() {
$users = array();
$sql = "SELECT id, username FROM users WHERE status = 'active' ORDER BY username";
$result = mysqli_query($connection, $sql);
while ($data = mysqli_fetch_array($result)) {
$users[$data->id] = $data->username;
}
return $users;
}
function following($user_id) {
$users = array();
$sql = "SELECT DISTINCT user_id FROM following WHERE follower_id = $user_id";
$result = mysqli_query($connection, $sql);
while ($data = mysqli_fetch_assoc($result)) {
array_push($users, $data->user_id);
}
return $users;
}
?>
Both files are inside an /includes folder. I now have a users.php files in which I want to display a list of users. Here's my code that tries to do that:
<?php
$users = show_users();
foreach ($users as $key => $value) {
echo $key . " " . $value;
}
?>
The problem I have is this:
Notice: Undefined variable: connection in
/Applications/MAMP/htdocs/blog/includes/functions.php on line 13
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in /Applications/MAMP/htdocs/blog/includes/functions.php on line 13
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
null given in /Applications/MAMP/htdocs/blog/includes/functions.php on
line 15
The users.php file has require('includes/functions.php') and require('includes/database.php'). But somehow the values are not passed?. What am I doing wrong? Please help me out. I hope this makes sense. The problem with the undefined variable occurs for each function of the 3.
Either pass the $connection variable to your functions or make it global.
E.g:
function show_posts($connection, $user_id) {
$posts = array();
$sql = "SELECT body, stamp from posts where user_id = '$user_id' order by stamp desc";
$result = mysqli_query($connection, $sql);
}
OR
function show_posts($user_id) {
global $connection;
$posts = array();
$sql = "SELECT body, stamp from posts where user_id = '$user_id' order by stamp desc";
$result = mysqli_query($connection, $sql);
}
Try $GLOBALS['connection'] instead of $connection in your function. See more here

Error when I passed on values on function

Sorry about the last post I had. Here's my revision, please help me.
<?php
//connect database
$sql = "SELECT * FROM user where user_id = 8320 AND password = 'admin' ";
$query = pg_query($sql);
var_dump($row = pg_fetch_array($query)); //dumps correctly.
?>
BUT THE PROBLEM IS THIS..when I try to make it as a function LIKE:
function check($user_id, $password)
{
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($sql);
$row = pg_fetch_array($query);
return $row;
}
AND CALL IT HERE:
var_dump($data = check(8320, 'admin')); DUMPS NULL;
How come it ended up like this?
Its returning NULL because there is an error with your SQL query, and no results are being returned. You should do some error checking in your function, try this version:
function check($user_id, $password)
{
$dbconn = pg_connect("host=localhost dbname=test");
$sql = "SELECT * FROM user where user_id = $1 AND password = $2 ";
$result = pg_query_params($dbconn, $sql, array($user_id,$password));
$row = pg_fetch_array($result);
if (!$row) {
echo pg_last_error($dbconn);
} else {
return $row;
}
}
Try the code below. It should work fine for you.
$data = check(8320, 'admin');
var_dump($data);
Seems like your PostgreSQL resource is missing inside the function. You have two options.
Declare the connection resource inside the function using global.
Establish the connection inside the function.
This is the first option:
$conn = pg_connect('host','user','pass','db');
function check($user_id, $password)
{
global $conn;
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
And this is the second option:
function check($user_id, $password)
{
$conn = pg_connect('host','user','pass','db');
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
According to the PHP manual, You may omit connection resource, but it is not recommended, since it can be the cause of hard to find bugs in scripts.

Categories