I'm trying to read directly from the Magento database through a custom script that looks like this:
require_once 'app/Mage.php';
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$conn = Mage::getSingleton('core/resource')->getConnection('core_read');
echo var_dump($conn);
function getAitocAttr() {
$test = $conn->fetchAll("SELECT * FROM customer_entity");
var_dump($test);
}
getAitocAttr();
Nothing is showing up when I run this script. What am I doing wrong? The error I'm receiving is:
Fatal error: Call to a member function fetchAll() on a non-object
Thanks
Looking at your error message
Fatal error: Call to a member function fetchAll() on a non-object
PHP is complaining about a method call to fetchAll on a non-object. Looking at your code, the only place you call fetchAll is here.
function getAitocAttr() {
$test = $conn->fetchAll("SELECT * FROM customer_entity");
var_dump($test);
}
Within the getAitocAttr function there's no $conn variable defined. When you say
$conn = Mage::getSingleton('core/resource')->getConnection('core_read');
you've defined $conn outside the scope of the getAitocAttr function. You'll need to either define $conn inside getAitocAttr, or declare $conn as global inside getAitocAttr for this to work.
I'm not sure what the problem with your script is exactly. It looks OK however I have tackled the problem slightly differently to this and it works for me.
require_once 'app/Mage.php';
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$conn = Mage::getSingleton('core/resource')->getConnection('core_read');
echo var_dump($conn);
function getAitocAttr()
{
$sql = "SELECT * FROM customer_entity";
$result = $conn->query($sql);
echo "<pre>";
while ($row = $readresult->fetch()) {
print_r($row);
}
}
getAitocAttr();
Related
I am unable to fetch record from a MySQL database using PHP. Here is my code.
user.php:
require_once ('../../include/dbconfig.php');
require_once ('common.php');
error_reporting(E_ALL);
ini_set('display_errors', '1');
$userClass=new CommonConnectorFuncs();
$redata=$userClass->insertUserRecordForSignup();
echo $redata;exit;
common.php:
require_once ('../../include/dbconfig.php');
error_reporting(E_ALL);
ini_set('display_errors', '1');
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") ? "https" : "http";
$imagepath=$protocol. "://" . $_SERVER['HTTP_HOST']."/connector/upload/";
class CommonConnectorFuncs{
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
public function insertUserRecordForSignup(){
$sql=mysqli_query($connect,"select * from cn_user_info order by user_id desc");
while ($row=mysqli_fetch_array($sql)) {
$data[]=$row;
}
return $data;
}
}
Here I am trying to fetch record and print through class but it's throwing the below message.
Notice: Undefined variable: connect in common.php on line 16
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in common.php on line 16
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in common.php on line 17
Notice: Undefined variable: data in common.php on line 20
Those query is working fine inside the user.php file but it's not working in common.php file.
As mentioned in comments, this is a scoping issue. Specifically, $connect is not in scope.
Notice: Undefined variable: connect in common.php on line 16
where connect is not defined anywhere.
Moreover, It's exactly as the error states as you're passing arguments to mysqli_query incorrectly. Assumming $connect is your mysqli connection generated at some point by new mysqli() it should be:
$sql = "select * from cn_user_info order by user_id desc";
$result = mysqli_query( $connect,$sql) or die('Could not look up user information; ' . mysqli_error($connect))
Hope it helps!
Make the connect variable a property of your class as by parsing it in your construct function
require_once ('../../include/dbconfig.php');
require_once ('common.php');
error_reporting(E_ALL);
ini_set('display_errors', '1');
$userClass=new CommonConnectorFuncs($connect);
$redata=$userClass->insertUserRecordForSignup();
echo $redata;exit;
In your class,
class CommonConnectorFuncs{
var $Connection;
function __construct($connection) {
try{
if($connection != null){
$this->Connection = $connection;
}else{
throw new Exception('Connection is null. COuld not process further');
}
}catch(Exception $ex){
echo $ex->getMessage();
exit;
}
}
// destructor
function __destruct() {
// $this->close();
}
public function insertUserRecordForSignup(){
$sql=mysqli_query($this->Connection,"select * from cn_user_info order by user_id desc");
while ($row=mysqli_fetch_array($sql)) {
$data[]=$row;
}
return $data;
}
}
The problem is in that you are trying to access a global variable within a function.
First of all, make sure you include the php file with the relevant database connection. And as you are trying to access a global variable there are two ways to achieve this.
Method 1
Create a global variable at the top of the function.
global $connect;
But as Qirel says in this comment, it is a bad practise, so I'd suggest the next.
Method 2
Pass the connection to the function's parameters.
public function insertUserRecordForSignup($connect){
$sql=mysqli_query($connect,"select * from cn_user_info order by user_id desc");
while ($row=mysqli_fetch_array($sql)) {
$data[]=$row;
}
return $data;
}
Hope you find this useful.
I'm new to OOP programming, and I'm really lost with this what the title says. When I try to put the query in a class and in another file, I get errors in a file called Main.php and don't even know what to do to fix them:
Notice: Undefined variable: sth in Select.php on line 10
Fatal error: Cannot access empty property in Select.php on line 10
If I put the select in Connection.php, it returns the rows just fine, but with classes, I get those.
Here's my code:
Connection.php:
<?php
$hostname = 'localhost';
$username = 'user';
$password = 'pass';
function connectDB ($hostname, $username, $password){
$dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
return $dbh;
}
$dbh = connectDB ($hostname, $username, $password);
echo 'Connected to database <br/>';
Select.php:
<?php require_once 'Connection.php';
class Select {
public function select() {
$sql= "select * from table limit 10; <br/>";
echo $sql;
$select = $dbh->query($sql)->fetchall(PDO::FETCH_ASSOC);
foreach($this->$sth as $row){
echo $row['column']."<br/>";
}
}
}
The question is, how can I print the result from the query (for example from main.php, which has an autoloader), and why do I get those errors, when on a single file, they work just fine?
Edit:
<?php
$test = new Select($dbh);
echo $test->select();
?>
Besides the fixes in the replies, I included Connection.php into the main.php, changed the echo in Select.php to return and it works perfectly now. Adding this in case someone ever gets as lost as me.
You do not want to iterate over the query, but the result of that query. So this probably is what you are looking for:
<?php
class Select {
public function select() {
$sql= 'select * from table limit 10';
$select = $dbh->query($sql)->fetchall(PDO::FETCH_ASSOC);
foreach($select as $row){
echo $row['column']."<br/>";
}
}
}
And you also need to take care that the $dbh object is actually present inside that method. Either inject it into the object or specify it as method argument. So your full class will probably look something like that:
<?php
class Select {
private $dbh;
public function __construct($dbh) {
$this->dbh = $dbh;
}
public function select() {
$sql= 'select * from table limit 10';
$select = $this->dbh->query($sql)->fetchall(PDO::FETCH_ASSOC);
foreach($select as $row){
echo $row['column']."<br/>";
}
}
}
And you instantiate the object like that:
$selectObj = new Select($dbh);
Some general warning, though: Using PDO's fetchall() method is convenient, but carries a huge risk: it means that the full result set has to be copied into an array inside the php script. For bigger results that may lead to issues with memory usage (scripts getting terminated for security reasons). Often it is the better approach to use a while loop over a single row fetched from the result set in each iteration.
I'm getting the error:
Call to a member function fetch() on a non-object
The line this refers to is:
$getProjectIdResult = $stmt->fetch();
Now, I think from this error that there must be something wrong with my database query, since the documentation says PDO query returns false on failure. I'm having trouble identifying what is causing the issue.
I've tried wrapping the fetch in a try/catch, with
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
However the catch isn't triggered and I just get the original fatal error so I haven't been able to get a more specific error.
classes.php
class Query extends Connection {
public function getProjectID($surveyID) {
$query_getProjectID = "SELECT projectID FROM test WHERE surveyID = :surveyID";
$query_getProjectID_params = array(
':surveyID' => $surveyID
);
try {
$stmt = $this->db->prepare($query_getProjectID);
$stmt = $stmt->execute($query_getProjectID_params);
}
catch (PDOException $ex) {
die("Failed to get project ID: " . $ex->getMessage());
}
$getProjectIdResult = $stmt->fetch();
$getProjectID = $getProjectIdResult['projectID'];
return $getProjectID;
}
}
test.php
include_once("includes/classes.php");
include_once("includes/functions.php");
// Bind $_GET data
// localhost/panel/test.php?surveyID=3&status=1&respondentID=666
// Expected result: 111
$surveyID = sanitise($_GET['surveyID']);
$status = sanitise($_GET['status']);
$respondentID = sanitise($_GET['respondentID']);
$con = new Connection();
$query = new Query();
$query->getProjectID($surveyID);
$con->closeConnection();
I've ruled out the sanitise function causing an issue by testing with and without it.
I apologise as I know this is probably just another amateur making another amateur mistake judging by how many posts there are by the same title.
When you call
$stmt = $stmt->execute($query_getProjectID_params);
You assign the return-value of execute() to $stmt, overwriting the variable, making it a boolean instead of an object. When you continue, $stmt no longer holds the PDOStatement object, but is now a boolean.
The solution is simply to remove the overwrite of your object, like this (remove $stmt = in front).
$stmt->execute($query_getProjectID_params);
http://php.net/pdostatement.execute
I'm having trouble setting up PDO in my website framework.
I open my connection in "system.php" which is included at the beginning of every page with this code here
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass,
array( PDO::ATTR_PERSISTENT => true));
}
catch(PDOException $e) {
echo $e->getMessage();
}
and on the same file (system.ph) I call this below it:
$STH = $DBH->query('SELECT value FROM settings WHERE type="theme"');
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
define('THEME', 'themes/'.$row['value'].'/');
}
Which works perfectly!
However, when I call the same query as above on "default.php" (which is included in the file) it comes back with:
Notice: Undefined variable: DBH in /pages/default.php on line 15
Fatal error: Call to a member function query() on a non-object
in /pages/default.php on line 15
What am I doing wrong here?
default.php
<?php
$STH = $DBH->query('SELECT value FROM settings WHERE type="theme"');
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) { echo $row['value']; }
?>
If it is inside a function add
global $DBH;
in the function before calling the query() function.
Seems like that file isn't getting included in default.php for whatever reason. Is there a boot strapper someplace that does the including for you before default.php is loaded?
Also, make sure that you're not getting an error on the path that loads default.php. It seems to me that $DBH would be undefined if there were an exception. Are you using output buffering someplace that might be cleared before you can see the echoing of the exception? You may want to consider logging your exceptions to a text file instead so that output buffering doesn't prevent you from seeing the errors which are occurring.
Have no idea whats going wrong here. Keeps throwing...
Fatal error: Call to a member function prepare() on a non-object
...every time it gets to the $select = $dbcon->prepare('SELECT * FROM tester1');part. Can somebody shed some light as to what I'm doing wrong?
function selectall() //returns array $client[][]. first brace indicates the row. second indicates the field
{
global $dbcon;
$select = $dbcon->prepare('SELECT * FROM tester1');
if ($select->execute(array()))
{
$query = $select->fetchall();
$i = 0;
foreach ($query as $row)
{
$client[$i][0] = $row['id'];
$client[$i][1] = $row['name'];
$client[$i][2] = $row['age'];
$i++;
}
}
return $client;
}
$client = selectall();
echo $client[0][0];
The obvious answer is that $dbcon hasn't been initialized at all or is initialized after this function is called.
What code is initializing $dbcon? Where and when is it run? You also realize that you will need to initialize it on every invocation of a script that accesses the database? The last is just to make sure that you understand what the global scope in PHP is. It means scoped to that single request. The term global is a little misleading.
make sure you define $dbcon properly. If you are using mysqli, see how the connection is setup in the doc. you can also pass the connection object to the function
function selectall($dbcon){
....
}