I have a func.php file that contains a function that gets my user's details:
require_once 'connection.php';
function getUI($username){
$query = "SELECT * FROM usernames WHERE username = ?";
$sth = $pdo->prepare($query);
$sth->bindValue(1, $username);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
return $result;
}
in my connection.php I have:
require_once 'details.php';
$pdo = new PDO("mysql:host=" . $dabhost . "; dbname=" . $dabname ."", $dabusern, $dabpassw);
and in details.php I have:
$dabhost = "localhost";
$dabname = "dab1";
$dabusern = "root";
$dabpassw = "root";
And ultimately, I have my userdetails.php that has a bunch of HTML code and displays the results that the function getUI() would bring back. I require func.php at the beginning:
require_once 'folder1/func.php';
My directory looks like this:
rootfolder/userdetails.php
rootfolder/folder1/details.php
rootfolder/folder1/connection.php
rootfolder/folder1/func.php
The issue is that when I open userdetails.php, I get an error in my php_error.log file that says the following:
PHP Notice: Undefined variable: pdo in /rootfolder/folder1/func.php on line 58
PHP Fatal error: Call to a member function prepare() on null in /rootfolder/folder1/func.php on line 58
Where if I were to just put all the code at the top of my userdetails.php, it would work and bring back the expected results. Therefore, there is something wrong with how I am requiring the files/scope of the variables I think...
Could someone explain to me what am I doing wrong?
Your help is much appreciated!
Thanks a lot!
UPDATE:
Passing my $pdo connection as a second argument in the function solved my proble, but now I am unable to retrieve x result from my returned $return variable, for instance:
echo $result['date'];
It says that the variable $result is not defined. Any idea why is this occurring?
Thanks a lot again!
When you declare
function getUI($username) {}
$pdo is not available because it is outside the scope of the function.
You'll need to pass it in as an additional parameter or find some other mechanism for getting $pdo inside getUI().
If you need more information
require_once 'connection.php';
function getUI($username,$pdo){
$result = null ;
$query = "SELECT * FROM usernames WHERE username = ?";
$sth = $pdo->prepare($query);
$sth->bindValue(1, $username);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
return $result;
}
Note : Pass PDO object as second parameter when you call above function.
Related
Hy everyone, I can't wrap my head around this. I'm trying to get some data from a table using PDO. this is my code:
//in db.php I have the connection:
$host = 'localhost';
$db = 'APL';
$dbuser = '';
$pass = ' ';
try{
$conn = new PDO("mysql:host=$host;dbname=$db", $dbuser, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
//in my file I have this:
$id = $_GET['id'];
$sel_sql = "SELECT * FROM users WHERE id =:id";
$stmt = $conn ->prepare($sel_sql);
$stmt -> bindParam(':id', $id);
$stmt -> execute();
$result = $stmt -> fetchAll(PDO::FETCH_ASSOC);
The problem is that print_r($result) returns '1' (just the value 1, therefore I can't access any data stored in the table) as long as $_SESSION['user'] is set.
The whole data-retrieving worked just fine if the $_SESSION['user'] is not set.
Can someone please explain why this is happening? (I'm fairly new to all this and I'm really trying to understand why some issues occur).
Thank you!
The fetchAll function should be returning either an array, or a boolean FALSE.
You report that print_r($result) is displaying an integer value of 1.
I don't see how that's possible, unless you are assigning a different value to $result. Try relocating print_r($result) to immediately follow the assignment from fetchAll.
(My suspicion is that $result is being assigned a value of 1 elsewhere in your code, before you do the print_r. If there were "Issues with php connection to MySQL database", we'd be expecting to see a PDO error of some sort.)
NOTE: I don't think PDO::FETCH_ASSOC is a defined fetch style for the fetchAll function. (fetchAll has different fetch styles than fetch.)
Just in case someone else stumbles upon this, between the $result variable and the print_r($result) I had an include_once(); statement (which was wrongly put there in the first place).
Thank you everyone for your answers.
This question already has answers here:
Giving my function access to outside variable
(6 answers)
Closed 8 years ago.
I have a problem. I am including my database details in my functions.php file. Like this:
db.php:
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "root";
$dbc = new PDO("mysql:host=" . $dbhost . "; dbname=" . $dbname ."", $dbuser, $dbpass);
functions.php:
include_once 'db.php';
function retrieve($count)
{
$query = "SELECT * FROM table WHERE column = ?";
$sth = $dbc->prepare($query);
$sth->bindValue(1, $count);
$sth->execute();
$resultCount = $sth->rowCount();
}
file.php:
include 'functions.php';
...
When I try to call my functions file in file.php, so I can use the function retrieve, my php_error.log file shows the following:
[Date] PHP Notice: Undefined variable: dbc in functions.php on line 6
My goal is to create an instance of PDO and use that in all the other pages so I don't have to create an instance over, and over again. I tried to achieve this by creating the $dbc variable and instancing a new PDO connection to it in db.php. Then, I would include it in functions.php so whenever a function is called, the $sth variable will hold the methods used, using $dbc (the instance of the PDO connection).
Does anyone know why am I getting this error, and possibly, could anyone give me some advice on how to parametrize the creation of an instance of PDO and use it/them throughout other pages?
Thank you for your time and help!
Cheers!
You have to pass the database connection to the function where your query is in order for it to work.
hoping someone can help me, I am having the following error, looked online and tried a load of things but can't seem to figure it out, error:
Fatal error: Call to undefined method mysqli::mysqli_fetch_all() in C:\xampp\htdocs\cyberglide\core-class.php on line 38
heres my code:
<?php
class Core {
function db_connect() {
global $db_username;
global $db_password;
global $db_host;
global $db_database;
static $conn;
$conn = new mysqli($db_host, $db_username, $db_password, $db_database);
if ($conn->connect_error) {
return '<h1>'."Opps there seems to be a problem!".'</h1>'.'<p>'."Your Config file is not setup correctly.".'</p>';
}
return $conn;
}
function db_content() {
//this requires a get, update and delete sections, before its complete
$conn = $this->db_connect();
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$query = "SELECT * FROM content";
// Escape Query
$query = $conn->real_escape_string($query);
// Execute Query
if($result = $conn->query($query)){
// Cycle through results
while($row = $conn->mysqli_fetch_all()){
//echo $row->column;
}
}
}
}
$core = new Core();
?>
I am trying to create a db_connect function, which I want to be able to call anywhere on the site that needs a database connection, I am trying to call that function on a function within the same class, I want it to grab and display the results from the database. I am running PHP 5.4.7, I am calling the database on a blank php file which includes a require to include the class file, then using this at the moment $core->db_content(); to test the function. I am building this application from scratch, running from MySQLi guides (not used MySQLi before, used to use normal MySQL query's) so if I am doing anything wrong please let me know, thanks everyone.
mysqli_fetch_all is a method of a mysqli_result, not mysqli.
So presumably it should be $result->fetch_all()
References:
http://php.net/manual/en/mysqli-result.fetch-all.php
Important: keep in mind mysqli_result::fetch_all returns the whole result set not a row as you assume in your code
There are three problems I see here.
while($row = $conn->mysqli_fetch_all()){
The method name is fetch_all() when used in the OOP way.
fetch_all() should be used with the $result object
fetch_all() is only available when the mysqlnd driver is installed - it frequently is not.
Reference
Only $result has that method. If you want to use it in a while loop use fetch_assoc(). fetch_all() returns an associative array with all the data already.
while($row = $result->fetch_assoc()){
}
thanks all, its working fine now, i had it as while($row = $conn->fetch_assoc()){
} before and changed to what i put above, but dident see it should of been $result instead of $conn, thanks for pointing that out.
I'm trying to use this script to see if there's a registered using in my database, but I'm having trouble on line 6. I keep getting the error:
Fatal error: Call to a member function bind_param() on a non-object in
-redacted-/check_login.php on line 6
I'm stumped as to why it's failing, because I have a similar statement working on the create user function.
<?php
ini_set('display_errors', 'On');
$db = new mysqli("localhost", "root", "-redacted-", "-redacted-");
$query = $db->prepare("SELECT user FROM users WHERE username = ? AND password = ?");
$query->bind_param('ss', $_POST['username'], md5($_POST['password']));
$query->execute();
$query->bind_result($result);
$query->fetch();
if($result->num_rows == 1) {
session_start();
$_SESSION['user'] = $_POST['username'];
header("Location: 10.0.0.15/index.php");
}
?>
This is usually caused by referencing a non-existant column/table in your database schema. Hence why the prepared is the root cause of this error.
What you should do, is check over your query. Making sure you are:
not using reserved mysql keywords
referencing columns/tables that
exist within the schema
There are no syntax errors within your SQL
Query
I have the following function:
class Forums {
public function getForum($id) {
$database = new Database();
$mysqli = $database->databaseConnection();
$stmt = $mysqli->prepare("SELECT name, description FROM forums WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
return $stmt;
}
}
I invoke it like this:
$forums = new Forums();
$result = $forums->getForum($_GET["id"]);
$result->bind_result($name, $description);
$result->fetch();
And then, since it returns only one row, call $name or $description whenever I need it.
However I get the following error in my browser (Chrome):
Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data."
This does not happen if I get rid of the function and connect to database and create prepared statement directly in the file where the result is used.
Why is this happening?
Looks like a variable scope issue. Object that holds $mysqli is destroyed directly after getForum() method execution. So open DB connection is destroyed at this moment too. But $result->fetch(); need to be connection still open.