Cannot redeclare conenect() error using PDO - php

I´m using pdo for my sql statements.
I have a connect.php file with this code:
<?php
function connect()
{
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = '';
$dbName = 'mysite';
try
{
$pdo = new PDO("mysql:dbname={$dbName};host={$dbHost}", $dbUser, $dbPass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
return $pdo;
}
?>
Now Im trying to use my connect.php in other php file like this:
include('../crud/config.php');
$pdo = connect();
And Im having this error:
Fatal error: Cannot redeclare connect() (previously declared in F:\Xampp\htdocs\projet\crud\config.php:9) in F:\Xampp\htdocs\projet\crud\config.php on line 32
Somebody there have some ideia why this is happening?
Maybe its because im using the statement like this with $pdo->
$verifyLevel = $pdo->prepare("SELECT * FROM administradores where id = :user");
$verifyLevel->bindValue(":user", $user);
$verifyLevel->execute();
$num_rows = $verifyLevel->rowCount();
$result = $verifyLevel->fetch(PDO::FETCH_ASSOC);
Because if I remove the $pdo = connect(); dont gives thar error but then gives other error but then because Im using $pdo->prepare to my sql statement I have an error because $pdo is not recognized without $pdo = connect()

Related

Error on calling a function with connection to SQL server

I am getting
Fatal error: Call to a member function query() on a non-object in
C:...\test.php on line 27
after calling callQuery2.
<?php
dbConnect();
callQuery1();
callQuery2();
function callQuery1(){
// SQL query
$q = "SELECT * FROM table1 WHERE name like 'john%' ";
// Execute query
$data1 = exeQuery($q);
}
function callQuery2(){
// SQL query
$q = "SELECT * FROM table2 WHERE event = 'holiday' ";
// Execute query
$data2 = exeQuery($q);
}
// Execute SQL Query
function exeQuery($qry) {
global $pdo;
####### LINE 27 #######
$stmt = $pdo->query($qry);
if($stmt = $pdo->prepare($qry)) {
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
return $data;
}
}
// database connection
function dbConnect(){
$DBSERVER = "***";
$DBUSER = "***";
$DBPASS = "***";
$DBNAME = "***";
// OBDC
try {
$pdo = new PDO("odbc:DRIVER={SQL Server};Server={$DBSERVER};Database={$DBNAME}", $DBUSER, $DBPASS);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//die(json_encode(array('outcome' => true)));
}
catch(PDOException $ex) {
//die(json_decode(array('outcome' => false, 'message' => 'Unable to connect')));
}
}
?>
Why the error only appears after at that time?
Is the a better way to do this?
Regards,
Elio Fernandes
This would be better encapsulated without the global $pdo; part. Instead return the PDO object from your connect method, and pass it to the others, to be used.
N.B. I've deliberately given the variables different names in different places, to illustrate that the name doesn't have to be the same when it's passed from one scope to another, it's the object that's passed which is important. You might perhaps consider using consistent names though, to make it easier to comprehend the code later, and trace the object through the flow.
<?php
$dbConn = dbConnect();
callQuery1($dbConn);
callQuery2($dbConn);
function callQuery1($db){
// SQL query
$q = "SELECT * FROM table1 WHERE name like 'john%' ";
// Execute query
$data1 = exeQuery($q, $db);
}
function callQuery2($db){
// SQL query
$q = "SELECT * FROM table2 WHERE event = 'holiday' ";
// Execute query
$data2 = exeQuery($q, $db);
}
// Execute SQL Query
function exeQuery($qry, $pdo) {
####### LINE 27 #######
$stmt = $pdo->query($qry);
if($stmt = $pdo->prepare($qry)) {
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
return $data;
}
}
// database connection
function dbConnect(){
$DBSERVER = "***";
$DBUSER = "***";
$DBPASS = "***";
$DBNAME = "***";
// OBDC
try {
$pdo = new PDO("odbc:DRIVER={SQL Server};Server={$DBSERVER};Database={$DBNAME}", $DBUSER, $DBPASS);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
catch(PDOException $ex) {
//die(json_decode(array('outcome' => false, 'message' => 'Unable to connect')));
}
}
?>

getting Call to a member function prepare() on null error when running SQL query in php and then printing out the results

i am trying to run the following piece of SQL code in a php file
Select show_id, show_name
From (tv_shows JOIN distributes on D_SHOW_ID=SHOW_ID)
Where show_name= ‘Show Name’
(where 'Show Name' is a variable the the user passes in.) The SQL functions perfectly in mySQL but i just can't seem to print the results without errors occurring.
i tried
$mysqli = include ('./DBconnect.php');
$sql = 'SELECT show_id, show_name
FROM (tv_shows JOIN distributes ON D_SHOW_ID=SHOW_ID)
WHERE show_name= ? ';
$stmt = $mysqli-> prepare($sql);
// getting the variable from the user input
$showName = $_GET["name"];
//testing if the variable is passed through
echo $showName."is printed";
$stmt->bind_param('s',$showName);
$stmt-> execute();
$stmt -> bind_result($show_id,$show_name);
if ($stmt->fetch())
{
echo '<p> Show ID: '.$show_id.' Show Name'. $show_name.'</p><br>';
}
and it is giving me a "Call to a member function prepare() on null " error
i have a second php file that is called DBconnect.php which also seem to function correctly.
function get_mysqli_conn(){
$dbhost = "xxxxx";
$dbuser = "xxxxx";
$dbpassword = "xxxxx";
$dbname = "xxxxxx";
$conn = new mysqli($dbhost, $dbuser,$dbpassword,$dbname);
if (!$conn){
die ('Failed to connec to MySQL : (' . $conn->connect_errno.')' . $conn ->connect_error);
}else{
echo 'connected';
}
}
1st : you need to use connection object .
$stmt = $mysqli-> prepare($sql);
change to
$stmt = $conn-> prepare($sql);
2nd : you just need to include it like below .
$mysqli = include ('./DBconnect.php');
change to
include ('./DBconnect.php');
3rd : your connection creation is inside the function so you need to call the function once and get the connection object like below .
include ('./DBconnect.php');
$conn = get_mysqli_conn();
4th : In that function you need to return the connection object like below .
function get_mysqli_conn(){
$dbhost = "xxxxx";
$dbuser = "xxxxx";
$dbpassword = "xxxxx";
$dbname = "xxxxxx";
$conn = new mysqli($dbhost, $dbuser,$dbpassword,$dbname);
if (!$conn){
die ('Failed to connec to MySQL : (' . $conn->connect_errno.')' . $conn ->connect_error);
}else{
return $conn;
}
}

How to build and call a simple PHP class for a PDO DB connection

Here's what I have so far:
class DB {
var $DBUser = 'xxx';
var $DBPass = 'xxx';
var $DBServer = 'xxx';
var $DBName = 'xxx';
public function connect() {
try {
$strDSN = "mysql:host=$this->DBServer;dbname=$this->DBName;";
$username = $this->$DBUser;
$pass = $this->$DBPass;
$conn = new PDO($strDSN, $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'connected';
}
catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
} //end method
} //end class
Which is then called using this:
$db = new DB;
$conn = $db->connect;
$stmt = $conn->prepare('SELECT * FROM XXX WHERE id = :id');
$id = $_GET['id'];
$stmt->execute(array('id'=>$id));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
However, I'm getting this error message:
Fatal error: Call to a member function prepare() on a non-object
Any ideas what I'm doing wrong?
When you call a method, include the parenthesis:
$conn = $db->connect();
// ^^ missing
The second problem is your connect method doesn't return the connection handle. In the try block add:
return $conn;
Finally, when referencing instance and class properties, don't include the $.
$username = $this->DBUser;
// ^ $ should not be present

php __construct what is wrong with this

What's wrong with my code:
class Database
{
private $db;
public function __construct()
{
$dbname = 'dbname';
$dbhost = 'localhost';
$dbuser = 'dbuser';
$dbpass = 'dbpass';
$connStr = "mysql:$dbhost; dbname=$dbname";
try
{
$this->db = new PDO($connStr, $dbuser, $dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (Exception $ex)
{
echo $ex->getMessage();
exit;
}
}
public function getTableFromSQLQuery($query, $params)
{
$db = $this->db;
$result = $this->db->prepare($query);
if (isset($params) && count($params)>0)
foreach($params as $key=>$param)
$result->bindParam ($key, $param);
$result->execute();
return $result->fetchAll(PDO::FETCH_ASSOC);
}
}
and call this from code:
$db = new Database();
$query = "SELECT * FROM mytable";
$rowsCategories = $db->getTableFromSQLQuery($query, null);
the error: Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected'
The problem in debugger it loses $db in class Database, why? If I each time use $db = new PDO(all params) it works, but if I use with constructor - it doesn't. Help, thanks
Connection string should be
$connStr = "mysql:host=$dbhost;dbname=$dbname";
Change $connStr to:
$connStr = "mysql:host=". $dbhost .";dbname=". $dbname;

Error calling member function "FETCH_ASSOC" - what is wrong with my code?

I am trying to connect to a PHP PDO and run a simple query on the data but I run into an error about the object not being created? I'm trying to make this as simple as possible and have been advised not to make a singleton database class and instead define the Database PDO whenever I need it, which is for this initial (simple) query.
Here is the error I am getting. What do I need to do to fix the code?
Fatal error: Call to a member function fetch() on a non-object in/home/...index.php on line 11
<?php
$dbhost = "localhost";
$dbname = "x";
$dbuser = "y";
$dbpass = "z";
$db = new PDO("mysql:host=$dbhost;db_name=$dbname", $dbuser, $dbpass);
$query = $db->query("SELECT * FROM tablename");
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
echo $row['field_name'],'<br>';
}
?>
And please let me know if you have a better way to select data from a mysql table using php. Trying to learn PDO and not mysqli. Thanks
You have to choose between ->query or ->fetch. You can't mix both method.
->query():
$sql = 'SELECT * FROM tablename';
foreach ($db->query($sql) as $row) {
echo $row['field_name'],'<br>';
}
->fetch():
$sth = $db->prepare("SELECT * FROM tablename");
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $row['field_name'],'<br>';
}
Probably there is a problem with the query, like a typo or the table does not exist.
Then $query is not a PDOStatement but false and you can't call false->fetch().
There's your typo:
$db = new PDO("mysql:host=$dbhost;db_name=$dbname", $dbuser, $dbpass);
Should be:
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
After fixing the typo this code works perfectly:
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$query = $db->query("SELECT * FROM wp_blogs");
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
var_dump($row).'<br>';
}

Categories