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){
....
}
Related
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 truly need your help. I have seen answers and even followed advice as previously posted but NO SOLUTIONS SHOW how to use fetch associated array using PREPARED STATEMENTS so I am not trying to submit an already answered question. I have followed suggestions to others questions but I am still getting:
Fatal error: Call to a member function fetch_assoc() on a non-object in /xxx/xxxxxx.php on line 75
I am showing you the old code using MySQL and how I have changed it to MySQLi using prepared statements, but I am still getting the same Fatal Error. Can someone please help me, I am going crazy and I truly need to find out what I am doing wrong. Thanks for your help.
//*******************************************************************
// OLD CODE:
// Called by: $theme=$log->get_theme();
//*******************************************************************
class redirect
{
function __construct()
{
}
function get_theme()
{
$rs=mysql_query("select * from theme where status='yes'");
if(mysql_num_rows($rs)>0)
{
$data=mysql_fetch_array($rs);
return $data['theme_name'];
}
}
}
//*********************************************************************
// OLD CODE:
// Called by: $theme=$log->get_theme($cn);
//*********************************************************************
class redirect
{
public $cn;
function __construct()
{
}
function get_theme($cn)
{
$themeStatus = 'yes';
if ($stmt = $cn->prepare("SELECT * FROM theme WHERE status = ? "))
{
$stmt->bind_param("s", $themeStatus);
$result = $stmt->execute();
$stmt->store_result();
if ($stmt->num_rows >= "1")
{
$data = $result->fetch_assoc(); // ERROR LINE
return $data['theme_name'];
}
}
else
{
echo "Failed to execute prepared statement: " . mysqli_connect_error();
}
}
}
The mysqli_stmt::execute method returns only bool by definition. So calling $result->any_method_name() will fail because $result is a boolean value.
To get the values from a prepared statement using the MySQLi library you bind your target variables with $stmt->bind_result(...) and then use $stmt->fetch() in a while loop to get the result of your query in your bound variables. And after that you switch from MySQLi to PDO because it has a better API regarding this…
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();
Below is my class. Fig A
<?php
class qcon{
public static $conn;
function dbcon()
{
if (!$conn)
{
$host = 'x';
$username = 'x';
$password = 'x';
$dbname = 'x';
$conn = mysqli_connect($host , $username , $password ,$dbname);
}
return $conn;
}
}
?>
Which is called here. Fig B
require_once(class file above);
function openSesame()
{
$boogey = new qcon();
$conn = $boogey->dbcon();
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
Is causing
Notice: Undefined variable: conn in C:\...\xxxx\figAclass.php on line 10
I know I can simply turn errors off, but this seems unwise. I took a look at a generic SO question about the undefined variable notice. Obviously the advice was general - use isset. Had a go at isset and this does not seem correct for what I am trying to do.
Based on the code in figure A and B, is there anything obvious causing the notice to be flagged up. Could you demonstrate a fix that is in line with the existing code shown.
Don't use if (!$conn), which will check to see if the variable is true/false or contains a value, not if it's defined. Use this instead:
if(empty($conn))
This checks to see if the variable is defined, and if it is NULL/empty.
You also want to use $this->conn inside of your class instead, since you're defining it as a variable of the class.
Like I said in my comment above, since you have a static $conn, you need to refer to it like:
public function dbconn()
{
if (!self::$conn) {
// blah
}
return self::$conn;
}
Your error is happening because you're attempting to reference a variable named $conn, but due to scope, no such thing exists.
when you access it, you should use $this->conn, in example:
if(!$this->conn){...}
edited read the question too fast, sorry
You can't use if (!$conn)for this because that will only return 'true' or 'false'.
Use:
if empty($conn) instead.