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;
?>
Related
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.
I have triggered the stored procedure from php. I have passed the input parameters also as shown.
$id = 1;
$nameDetail = 'raj';
$result = mysqli_query('CALL InsertDetails($id,$nameDetail)');
But getting below error.
mysqli_query() expects at least 2 parameters, 1 given ...
Please suggest a solution.
The issue is that you're not set the mysqli connection.please try this
$connection = mysqli_connect('localhost','username','password','db');
$result = mysqli_query($connection,'CALL InsertDetails($id,$nameDetail)');
You need to pass in the connection as the first parameter:
// connect to DB
$connect = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
// run procedure
$result = mysqli_query($connect, 'CALL InsertDetails($id,$nameDetail)');
I have the following code for test, and I just found the 2nd parameter is not actually working.
$conn1 = mysql_connect("127.0.0.1", "xxxx", "xxxx");
$conn2 = mysql_connect("127.0.0.1", "xxxx", "xxxx");
mysql_select_db("test", $conn1);
mysql_select_db("yangshengfun", $conn2);
if (!$res = mysql_query("select * from proxy_ips limit 1", $conn1)) {
echo mysql_error($conn1);
}
if (!$res = mysql_query("select * from wp_posts limit 1", $conn2)) {
echo mysql_error($conn2);
The tables in database 'test' and 'yangshengfun' are complately different.
An error occured while I run this code:
Table 'yangshengfun.proxy_ips' doesn't exist
Seems when I call mysql_select_db for $conn2, it changes the current db of $conn1 too, any ideas?
try this
$conn1= mysql_connect("host_name", "user_name", "pass_word") or die('not connected');
mysql_select_db("database_name", $conn1);
Here the "die($message)" function prints a message if mysql_connect() function can't connect with db.
try this
$conn1 = mysql_connect("127.0.0.1", "xxxx", "xxxx", true);
$conn2 = mysql_connect("127.0.0.1", "xxxx", "xxxx", true);
Note : mysql_* is deprecated. use mysqli_* or pdo
Use mysqli instead:
<?php
$conn1 = new mysqli(host, user, password, db);
$conn2 = new mysqli(host2, user2, password2, db2);
?>
From the documentation of mysql_connect() of the PHP Manual
If a second call is made to mysql_connect() with the same arguments,
no new link will be established, but instead, the link identifier of
the already opened link will be returned. The new_link parameter
modifies this behavior and makes mysql_connect() always open a new
link, even if mysql_connect() was called before with the same
parameters. In SQL safe mode, this parameter is ignored.
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, Prepared Statements of MySQLi or PDO_MySQL extension should be used to ward off SQL Injection attacks !
So I have a PHP page that connects first to my database and does a bunch of stuff using the information from there. Now I want to connect to another database within the same PHP page and access data from there and insert the information into my original database.
The code:
<?php
session_start();
include ("account.php");
include ("connect.php");
....
do stuff here
....
include ("account2.php");
include ("connect2.php");
...
$thing = "SELECT abc, efg, hij FROM table ORDER BY RAND() LIMIT 1" ;
$thing = mysql_query($thing);
echo "$thing";
....
....
insert information into my database
(From account.php & connect.php files)
....
?>
Everything shows up except for $thing. It says, "Invalid query: Query was empty" but I know the query I used works because when I ran it in the account2 database, I got the results I wanted. Is there something wrong with my logic or is it something else?
You are not mentioning database connection link while executing the query. May be your second database connection is defined after the 1st one in connection.php file. So interpreter is considering 2nd connection while executing the query.
Define the connection link with query,
$thing = mysql_query($thing,$conn); //$conn is your mysql_connect
You can still use the mysql_connect or similar mysql_ functions (procedural way) But all these are now deprecated. You should use mysqli_ (mysql improved) functions or go with the object oriented way.
$conn1 = new mysqli(SERVER1,DB_USER1,DB_PASS1,DB1);
$conn2 = new mysqli(SERVER2,DB_USER2,DB_PASS2,DB2);
if($conn1 ->connect_errno > 0 || $conn2 ->connect_errno > 0){
die('Unable to connect to database server.');
}
Now while executing your query,
$query = "SELECT abc, efg, hij FROM table ORDER BY RAND() LIMIT 1";
$thing = $conn1 -> query($query); //if it's second connection query user $conn2
Many web applications benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.
For your case, i would make 2 persistent connections, store each in it's own variable and then use one whenever i need to. Check it out using the PDO class.
//Connection 1
$dbh1 = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
.
.
.
//Connection 2
$dbh2 = new PDO('mysql:host=localhost;dbname=test2', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
After you finish you first database operation, then you can close the connection using
mysql_close($c) //$c = connection
And again start for next database operation.
private static function _connectDB1()
{
//give hostname, dbusername, dbpassword
$con1 = mysql_connect("localhost", "root", "rootpass");
$db1 = mysql_select_db("dbone", $con1);
}
private static function _connectDB2()
{
//if you are using different db with different credentials
//you can give here like this
// mysql_connect("mynewhost", "mynewusername", "mynewpassword")
$con2 = mysql_connect("localhost", "root", "rootpass");
$db2 = mysql_select_db("dbtwo", $con2);
}
I want to select a MySQL database to use after a PHP PDO object has already been created. How do I do this?
// create PDO object and connect to MySQL
$dbh = new PDO( 'mysql:host=localhost;', 'name', 'pass' );
// create a database named 'database_name'
// select the database we just created ( this does not work )
$dbh->select_db( 'database_name' );
Is there a PDO equivalent to mysqli::select_db?
Perhaps I'm trying to use PDO improperly? Please help or explain.
EDIT
Should I not be using PDO to create new databases? I understand that the majority of benefits from using PDO are lost on a rarely used operation that does not insert data like CREATE DATABASE, but it seems strange to have to use a different connection to create the database, then create a PDO connection to make other calls.
Typically you would specify the database in the DSN when you connect. But if you're creating a new database, obviously you can't specify that database the DSN before you create it.
You can change your default database with the USE statement:
$dbh = new PDO("mysql:host=...;dbname=mysql", ...);
$dbh->query("create database newdatabase");
$dbh->query("use newdatabase");
Subsequent CREATE TABLE statements will be created in your newdatabase.
Re comment from #Mike:
When you switch databases like that it appears to force PDO to emulate prepared statements. Setting PDO::ATTR_EMULATE_PREPARES to false and then trying to use another database will fail.
I just did some tests and I don't see that happening. Changing the database only happens on the server, and it does not change anything about PDO's configuration in the client. Here's an example:
<?php
// connect to database
try {
$pdo = new PDO('mysql:host=huey;dbname=test', 'root', 'root');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $err) {
die($err->getMessage());
}
$stmt = $pdo->prepare("select * from foo WHERE i = :i");
$result = $stmt->execute(array("i"=>123));
print_r($stmt->fetchAll(PDO::FETCH_ASSOC));
$pdo->exec("use test2");
$stmt = $pdo->prepare("select * from foo2 WHERE i = :i AND i = :i");
$result = $stmt->execute(array("i"=>456));
print_r($stmt->fetchAll(PDO::FETCH_ASSOC));
If what you're saying is true, then this should work without error. PDO can use a given named parameter more than once only if PDO::ATTR_EMULATE_PREPARES is true. So if you're saying that this attribute is set to true as a side effect of changing databases, then it should work.
But it doesn't work -- it gets an error "Invalid parameter number" which indicates that non-emulated prepared statements remains in effect.
You should be setting the database when you create the PDO object. An example (from here)
<?php
$hostname = "localhost";
$username = "your_username";
$password = "your_password";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
echo "Connected to database"; // check for connection
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Alternatively, you can select a MySQL database to use after a PHP PDO object has already been created as below:
With USE STATEMENT. But remember here USE STATEMENT is mysql command
try
{
$conn = new PDO("mysql:host=$servername;", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("use databasename");
//application logic
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
I hope my code is helpful for requested
As far as I know, you have to create a new object for each connection. You can always extend the PDO class with a method which connects to multiple databases. And then use it as you like:
public function pickDatabase($db) {
if($db == 'main') {
return $this->db['main']; //instance of PDO object
else
return $this->db['secondary']; //another instance of PDO object
}
and use it like $yourclass->pickDatabase('main')->fetchAll('your stuff');