How to connect to mysql using pdo - php

I am working on my php as I want to connect to the mysql database using PDO. I have stored the username, password and database in the config file, but I have got a problem with connecting to the mysql database because I keep getting an error.
When I try this:
<?php
//Connect to the database
include('config.php');
$smtps = $link->query('SELECT * FROM sent');
$smtps->execute();
$db = $smtps->get_result();
print($db);
?>
I am getting an error:
Fatal error: Uncaught Error: Call to undefined method
PDOStatement::get_result() in
/home/username/public_html/test_pdo.php:17 Stack trace: #0 {main}
thrown in /home/username/public_html/test_pdo.php on line 17
Here is the line 17:
$db = $smtps->get_result();
Here is the config:
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'dbtablename');
//$errflag = false;
$link = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASS);
?>
Can you please show me an example how do you connect to mysql database using PDO when you stored the username, password and database name in config.php?
Thank you.

This is happening because get_result() is not a PDO method.
In this situation you should just use fetch() (link) if you just want the first result or fetchAll() (link) if you want an array of the results
Try this:
$smtps = $link->query('SELECT * FROM sent');
$result = $smtps->fetchAll();
print($result);
You only need to use the excute() when using parameters in your select:
SELECT * FROM sent where id = ?
would be
$smtps = $link->prepare('SELECT * FROM sent where id = ?');
$smtps->execute([$id]);
$result = $smtps->fetch();
print($result);

If u use query method u can without execute method get result as as below cod
include('config.php');
$result = $link->query('SELECT * FROM sent')->fetchAll(PDO::FETCH_ASSOC);
print_r($result);

get_results is not a method of the PDO class. If you want to fetch data from the database in this case, use fetchAll() method of the query object.
<?php
//Connect to the database
include('config.php');
$smtps = $link->query('SELECT * FROM sent');
$smtps->execute();
$db = $smtps->fetchAll();
print($db);
?>
Hope that helps.

Related

how to select specific field from a database using mdb2 php?

I'm trying to select a specific ID that is auto-generated by the oracle database for a specific session user(from log in and its working fine). I'm using MDB2 to achieve this. I am following the pear: MDB2 manual and did the codes the way it is but I'm getting an error. Please help.
I have used the fetchOne(MDB2_FETCHMODE_ASSOC) to achieve this from the reading manual and its giving an error
<?php
session_start();
$user = $_SESSION['user'];
echo "Welcome:\t".$user;
require_once 'MDB2.php';//pear MDB2
include "conn.php";
$do= "SELECT customer_id FROM customer WHERE username=".$user;
$query= $db->query($do);
if($one=$query->fetchOne(MDB2_FETCHMODE_ASSOC)){
$id= $one['customer_id'];
echo ($id);
}
?>
The number 2 should be printed out but instead there this error:
Fatal error: Call to undefined method MDB2_Error::fetchOne() in C:\wamp64\www\grahams\home.php on line 12
Try using below code.
<?php
session_start();
$user = $_SESSION['user'];
echo "Welcome:\t".$user;
require_once 'MDB2.php';//pear MDB2
include "conn.php";
$do= "SELECT customer_id FROM customer WHERE username=".$user;
$id = queryOne($do);
if(isset($id))
{
echo $id;
}
?>
Since queryOne() query the database and select the column from the given query.
Edit:
in conn.php check whether the connection is okay. following is the example code.
<?php
$dsn = array(
'phptype' => 'oci8',
'hostspec' => null,
'username' => 'oci_username',
'password' => 'oci_password',
);
// Establish database connection
$db = MDB2::connect($dsn);
// Check if the connection was established successfully
if (PEAR::isError($db)) {
die('Could not create database connection. "'.$db->getMessage().'"');
}
?>

PDO is unable to fetch database name on SQL queries

I am trying to connect to the database via PDO and my db.php file is as follows:
$host = "localhost";
$db = "mydb";
$user = "user";
$pass = "qRES2fIWK8Gg";
try
{
$db = new PDO("mysql:host = $host; dbname = $db", $user, $pass);
$db -> exec ("SET NAMES utf8"); // charset = utf8 doesn't work.
echo "Database connection is successful. <br>";
}
catch (PDOException $e)
{
echo $e -> getMessage();
}
I have two problems which I think there is a connection between them.
When I check the db.php, I can get Database connection is successful message even though I change the host and dbname with random and incorrect values. How is that possible? When I try the same process on the database username and password, it gives an error.
I am unable to run SQL queries without stating database name in it as PDO
doesn't fetch database name from db.php. For example, this SQL query
doesn't work:
SELECT * FROM settings WHERE settings_id= :id
However, this one works successfully:
SELECT * FROM mydb.settings WHERE settings_id= :id
I was working on localhost. After this problem, I thought it has been related to localhost and I moved my project to a virtual host. However, this step hasn't fixed the problems.
Removing the spaces in your DSN string should resolve your issues:
"mysql:host=$host;dbname=$db"

Function file will not recognize included PDO database connection

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.

PHP MySQL call Store Procedure with parameters

In my php application i need to call a stored procedure from MySQL
the procedure i have created is this.
DROP PROCEDURE IF EXISTS _proc.usp_hotel_rooms_mLoadByPrimaryKey;
CREATE PROCEDURE _proc.`usp_hotel_rooms_mLoadByPrimaryKey`(
_HTR_ID INT(11),
_HTR_TYPE_ID INT(11)
)
BEGIN
SELECT
HTR_ID,
HTR_NAME,
HTR_TYPE_ID
FROM hotel_rooms_m
WHERE
(HTR_ID = _HTR_ID AND HTR_TYPE_ID=_HTR_TYPE_ID)
;
END;
I need to pass the parameters _HTR_ID and _HTR_TYPE_ID,so i tried it like this
<?php
$con = mysql_connect("localhost","user","user")or die(mysql_error());
$db = mysql_select_db("_proc") or die(mysql_error());
$par1 = "1";
$par2 = "2";
$dbh->query("CAST usp_hotel_rooms_mLoadByPrimaryKey($par1, $par2, #OutPut)");
$dbh->query("SELECT #OutPut");
echo $dbh;
?>
this is the error i am getting Call to a member function query() on a non-object in D:\xampp\htdocs\_proc\index.php on line
You have to use
your connection string like this using mysqli
$mysqli = new mysqli( "HOST", "USR", "PWD", "DBNAME" );
Here is the link for tutors Mysql stored procedures with php
You seem to be mixing up some styles: Nor mysql_connect nor mysql_select_db return an object and all mysql_* functions are deprecated. Your $dbh->query statments seem to suggest a database connection using mysqli or PDO.
You probably want to open a connection using mysqli or PDO to start with and assign that to your $dbh variable.
Here your code goes
<?php
$dbh = new PDO('mysql:host=localhost;dbname=_proc', "user", "user");
$par1 = "1";
$par2 = "2";
$dbh->query("CAST usp_hotel_rooms_mLoadByPrimaryKey($par1, $par2, #OutPut)");
$dbh->query("SELECT #OutPut");
echo $dbh;
?>

What is corret way to connect to MySQL? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result
what is the correct way to connect to MySQL database without the mysql_fetch_assoc() error?
Getting [Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource] with
mysql_connect('localhost', 'name', 'pass'); mysql_select_db('dbname');
getting mysql_fetch_assoc() error without mysql_select_db any suggest?
CODE are:
var somethings= ;
Typo? Your question has msyql_select_db instead of mysql_select_db - note the swap of the s and y in mysql.
Try:
$result= mysql_query('SELECT DISTINCT username FROM users');
$somethings= array();
while ($row= mysql_fetch_assoc($result)) {
$somethings[]= $row['something'];
}
Basically changing $results to $result.
$connect = mysql_connect('host', 'user', 'pass);
mysql_select_db('database', $connect);
That's how you connect to a database.
You also spelled mysql wrong.
Getting Fatal error: Call to undefined function msyql_select_db() with mysql_connect('localhost', 'name', 'pass'); <<msyql>>_select_db('dbname');
Arrows around the error.
you spelled your function incorrectly mysql not msyql
I do not understand your question, but maybe this will help.
$session = mysql_connect('host','username','password');
mysql_select_db('database', $session);
$resultset = mysql_query('SELECT * FROM TABLE', $session);
$result = mysql_fetch_assoc($resultset);
Good luck...
May want to change localhost to '127.0.0.1' as well...I've had issues with that before.
<?php
$result= mysql_query('SELECT DISTINCT username FROM users');
while ($row= mysql_fetch_assoc($results)) {
$somethings[] .= $row['something'];
}
?>
Try this
<?php
DEFINE ('DB_USER', ''); //specify the DB username like root.
DEFINE ('DB_PASSWORD', ''); //specify the DB password.
DEFINE ('DB_HOST', ''); //specify the DB hostname(localhost of IP address).
DEFINE ('DB_NAME', ''); //specify the DB Name on which your doing operations.
$dbc = #mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' .mysqli_connect_error() );
$query="Specify your operation in a query format";
#mysqli_query($dbc,$query);
#mysqli_close($dbc);
?>

Categories