I can't seem to use a array in a PDO statement here. It connects to the SQL Server properly, I just removed the user pass for security. When I run this script, it returns:
Call to undefined method PDOStatement::prepare()
I have no idea what I'm doing wrong. I've researched everywhere. Any help would be appreciated.
<?php
$hello = "foo";
try {
$bdd = new PDO("mysql:host=sql213.byethost16.com;dbname=b16_16742662_main", "b16_16742662", "00163827");
} catch(Exception $e){
die("ERROR : ".$e->getMessage());
}
$req = $bdd->prepare("SELECT * FROM ajax_chat_registered_members WHERE NAME=:UserName AND PASS=:UserPass");
$req->prepare(array('UserName'=>"Test",'UserPass'=>"foo"));
?>
Related
Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Manager::listDatabases()
this error keep showing when i wanted to use the administration command for mongodb using php. I do not know whats the problem here and someone with kind soul please help me. The following codes is what i have tried which cause that error.
<?php
$client = new MongoDB\Driver\Manager( 'mongodb+srv://'.$_ENV['MDB_USER'].':'.$_ENV['MDB_PASS'].'#'.$_ENV['ATLAS_CLUSTER_SRV'].'/test'
);
try{
$dbs = $client->listDatabases();
echo '<pre>';
print_r($dbs);
echo '</pre>';
// Or Nothing if you just wanna check for errors
}
catch(Exception $e){
echo "Unable to connect to Database at the moment ! ";
exit();
}
$colecciones = $client->listCollections();
foreach ($colecciones as $col) {
echo $col->getName();
}
?>
these two are the refereces that i used but is not working for me
Get collections in mongodb with PHP
Is there a way to test MongoDB connection in PHP?
what i am trying to do here is to make sure that my database connection is successful and also list out the collection name of my mongodb database.`
You are trying to call an undefined method in the MongoDB\Driver\Manager class
You can see the list of methods and functions here
https://www.php.net/manual/en/class.mongodb-driver-manager.php
In addition please follow all the listed function and methods in php mongodb driver.
Try to use this to query data from the database:
$manager = new MongoDB\Driver\Manager('mongodb+srv://'.$_ENV['MDB_USER'].':'.$_ENV['MDB_PASS'].'#'.$_ENV['ATLAS_CLUSTER_SRV'].'/test'
);
$filter = [];
$option = [];
$read = new MongoDB\Driver\Query($filter, $option);
$query = $mongo->executeQuery(‘db.Collection_Name’ $read);
$exportQuery = $query->toArray();
var_dump($exportQuery);
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've been trying to use a sqlite database (php with PDO), but have been running into a problem. Generally the commands work, and everything is fine (including storing files), but for some reason when I run these two commands (which have been simplified), I get the error
SQLSTATE[HY000]: General error: 5 database is locked
I've tried for a while, but have been unable to fix whatever is wrong. The code is below.
Things I've done:
Tried to put sleep(2) between commands
Found out that commenting either of the commands out will cause the error not to happen (which doesn't really help, as both commands must run)
Note that (unlike other problems I saw while looking at similar questions) the database operates correctly in other cases.
$db = new MyDB();
$STH = $db->catchMistakes('SELECT PASSWORD FROM USERS WHERE USERNAME = ?', "test");
$STH->fetchColumn();
$db->catchMistakes("UPDATE ISSUES SET NAME = ? WHERE NUM = ?", ["test", "1"]);
And here's the code for MyDB
public function catchMistakes($cmd, $params = []) {
if (!is_array($params)) {
$params = [$params];
}
try {
$DBH = new PDO("sqlite:" . DB);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$DBH->beginTransaction();
$query = $DBH->prepare($cmd);
$toReturn = $query->execute($params);
$DBH->commit();
return $query;
}
catch(PDOException $e) {
$DBH->rollback();
$error = $e->getMessage();
exit;
}
}
Sorry if there's a simple fix, I'm pretty new at this. Any help would be greatly appreciated.
You can use closeCursor() method on a PDOStatement object to free the connection to the database so the statement can be executed. You can refer to the PHP manual.
I have the following code, I am unable to figure out why the PDO statement error occurs, here is my code
try {
$db = new PDO("mysql:dbname=imdb","username","pwd");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$first_name=$db->quote($first_name);
$last_name=$db->quote($last_name);
$row_id=$db->query("SELECT id FROM actors WHERE last_name=$last_name AND first_name LIKE ${first_name} ORDER BY film_count DESC LIMIT 1");
if ($row_id->rowCount() > 0) {
$idrow=$row_id->fetch_assoc();
print_r($idrow);
return $row_id;
}
else {
return Null;
}
}
catch (PDOException $ex) {
?>
<p>Sorry, a database error occurred. Please try again later.</p>
<p>(Error details: <?= $ex->getMessage() ?>)</p>
<?php
return NULL;
}
I get this error when I run
Fatal error: Call to undefined method PDOStatement::fetch_assoc()
Any help?
Because just like the error says. fetch_assoc() isn't defined.
You want
$row_id->fetch(PDO::FETCH_ASSOC)
fetch() is the correct method name and you pass it one of the PDO Constants to determine what type of variable to get back.
I'm using the following script to use a database using PHP:
try{
$db = new PDO('mysql:host='.$host.';port='.$port.';dbname='.$db, $user, $pass, $options);
}
catch(Exception $e){
$GLOBALS['errors'][] = $e;
}
Now, I want to use this database handle to do a request using this code:
try{
$query = $db->prepare("INSERT INTO users (...) VALUES (...);");
$query->execute(array(
'...' => $...,
'...' => $...
));
}
catch(Exception $e){
$GLOBALS['errors'][] = $e;
}
Here is the problem:
When the connection to the DB is OK, everything works,
When the connection fails but I don't use the DB, I have the $GLOBALS['errors'][] array and the script is still running afterwards,
When the connection to the DB has failed, I get the following fatal error:
Notice: Undefined variable: db in C:\xampp\htdocs[...]\test.php on line 32
Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs[...]\test.php on line 32
Note: Line 32 is the $query = $db->prepare(...) instruction.
That is to say, the script crashes, and the try/catch seems to be useless. Do you know why this second try/catch don't works and how to solve it?
Thanks for the help!
EDIT: There are some really good replies. I've validated one which is not exactly what I wanted to do, but which is probably the best approach.
try/catch blocks only work for thrown exceptions (throw Exception or a subclass of Exception must be called). You cannot catch fatal errors using try/catch.
If your DB connection cannot be established, I would consider it fatal since you probably need your DB to do anything meaningful on the page.
PDO will throw an exception if the connection cannot be established. Your specific problem is that $db is not defined when you try to call a method with it so you get a null pointer (sort of) which is fatal. Rather than jump through if ($db == null) hoops as others are suggesting, you should just fix your code to make sure that $db is either always defined when you need it or have a less fragile way of making sure a DB connection is available in the code that uses it.
If you really want to "catch" fatal errors, use set_error_handler, but this still stops script execution on fatal errors.
In PHP7, we now can using try catch fatal error with simple work
try {
do some thing evil
} catch (Error $e) {
echo 'Now you can catch me!';
}
But usualy, we should avoid using catch Error, because it involve to miss code which is belong to programmer's reponsibility :-)
I will not report what has already been written about testing if $db is empty. Just add that a "clean" solution is to artificially create an exception if the connection to the database failed:
if ($db == NULL) throw new Exception('Connection failed.');
Insert the previous line in the try - catch as follow:
try{
// This line create an exception if $db is empty
if ($db == NULL) throw new Exception('Connection failed.');
$query = $db->prepare("INSERT INTO users (...) VALUES (...);");
$query->execute(array(
'...' => $...,
'...' => $...
));
}
catch(Exception $e){
$GLOBALS['errors'][] = $e;
}
Hope this will help others!
If database connection fails, $db from your first try .. catch block will be null. That's why later you cannot use a member of non-object, in your case $db->prepare(...). Before using this add
if ($db) {
// other try catch statement
}
This will ensure that you have db instance to work with it.
Try adding the following if statement :
if ($db) {
$query = $db->prepare("INSERT INTO users (...) VALUES (...);");
$query->execute(....);
}
else die('Connection lost');
try{
if(!is_null($db))
{
$query = $db->prepare("INSERT INTO users (...) VALUES (...);");
$query->execute(array(
'...' => $...,
'...' => $...
));
}
}
catch(Exception $e){
$GLOBALS['errors'][] = $e;
}