I've recently started working with mysqli.
Previously with php and MySQL I would write a common class holding the MySQL database connection as I don't want to repeat that code over and over.
Now with mysqli I can't seem to do this.
Is there a simple way to do this I think I'm missing something really obvious.
Have you considered using PDO?
Example:
session_start();
$db_user = 'example';
$db_pass = 'xxxxx';
$user_id = 1;
try
{
$db=new PDO( "mysql:host={$db_host}dbname={$db_name}", $db_user, $db_pass);
}
catch ( Exception $e )
{
exit( "Error connecting to database: " . $e->getMessage() );
}
$statement = $db->prepare( "SELECT * FROM user WHERE user_id=:user_id" );
// http://www.php.net/manual/en/pdostatement.bindvalue.php
$statement->bindValue( ':user_id', $user_id, PDO:: PARAM_INT );
$statement->execute();
// http://www.php.net/manual/en/pdostatement.fetch.php
// fetches an object representing the db row.
// PDO::FETCH_ASSOC is another possibility
$userRow = $statement->fetch( PDO::FETCH_OBJ );
var_dump( $userRow );
Related
I have pleasure to work with legacy PHP application using SQL Server via PDO.
How in PHP can I retrieve return value of stored procedure which is using RETURN statement as output channel?
Example procedure
CREATE PROCEDURE [dbo].[mleko_test]
#param INT
AS
BEGIN
RETURN #param * 3;
END
GO
If possible, I would prefer to not modify procedure.
I am aware that there are similar questions, but they don't cover this case
Get RETURN value from stored procedure in SQL
Get Return Value from SQL Stored Procedure using PHP
Execute stored procedure like this: "exec ?=mleko_test(?)".
Working example:
<?php
#------------------------------
# Connection info
#------------------------------
$server = 'server\instance,port';
$database = 'database';
$uid = 'user';
$pwd = 'password';
#------------------------------
# With PDO
#------------------------------
try {
$conn = new PDO("sqlsrv:server=$server;Database=$database", $uid, $pwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch ( PDOException $e ) {
die ( "Error connecting to SQL Server" );
}
try {
$sql = "exec ? = mleko_test (?)";
$param = 3;
$spresult = 0;
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $spresult, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT, PDO::SQLSRV_PARAM_OUT_DEFAULT_SIZE);
$stmt->bindParam(2, $param);
$stmt->execute();
} catch ( PDOException $e ) {
die ( "Error connecting to SQL Server" );
}
$stmt = null;
$conn = null;
echo 'Stored procedure return value (with PDO): '.$spresult."</br>";
#------------------------------
# Without PDO
#------------------------------
$cinfo = array (
"Database" => $database,
"UID" => $uid,
"PWD" => $pwd
);
$conn = sqlsrv_connect($server, $cinfo);
if ( $conn === false )
{
echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
exit;
}
$sql = "exec ? = mleko_test (?)";
$param = 3;
$spresult = 0;
$params = array(
array(&$spresult, SQLSRV_PARAM_OUT),
array($param, SQLSRV_PARAM_IN),
);
$stmt = sqlsrv_query($conn, $sql, $params);
if ( $stmt === false ) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
echo 'Stored procedure return value (without PDO): '.$spresult."</br>";
?>
Notes:
Tested with PHP 7.1.12 and PHP Driver for SQL Server (pdo_sqlsrv version 4.3.0+9904).
I came to a solution using multi-query but #Zhorov answer is cleaner
<?php
$connection = new PDO($connectionString, $DB_USERNAME, $DB_PASSWORD);
$stmt = $connection->prepare(<<<SQL
DECLARE #a INT;
EXEC #a = mleko_test :in
SELECT #a AS result;
SQL
);
$stmt->execute([":in" => 123]);
echo $stmt->fetch()["result"] . "\n";
I had to change
$sql = "exec ?=mleko_test(?)";
for
$sql = "{?=call mleko_test(?)}";
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I tried to look for questions with the same issue but I couldn't get their solutions to fit my code.
I keep getting the error:
Object of class mysqli could not be converted to string in line 5
Code:
<?php
function aggiornamento($utente) {
global $conn;
global $_CONFIG;
$selezione = mysqli_query ($conn, "SELECT * FROM ".$_CONFIG['db_account'].".account WHERE login = '".$utente."' LIMIT 1");
while ($account = mysqli_fetch_array($selezione)) {
$_SESSION['IShop_Login']= $account['login'];
$_SESSION['IShop_DR'] = $account['dr'];
$_SESSION['IShop_DB'] = $account['db'];
$_SESSION['IShop_AID'] = $account['id'];
$_SESSION['IShop_Admin'] = $account['Admin_IShop'];
}
}
?>
I tried a few solutions from already asked questions but to no avail. So I'm kindly asking you to correct my code for me and maybe a little explanation of what's going on so I'd learn.
My $conn:
$conn = mysql_connect($_CONFIG['host'], $_CONFIG['user'], $_CONFIG['pass']);
Whereas $_CONFIG['host'], $_CONFIG['user'], $_CONFIG['pass'] defined as:
$_CONFIG['host'] = "SERVER IP";
$_CONFIG['user'] = "root";
$_CONFIG['pass'] = "PW";
And most importantly, $_CONFIG['db_account'] = "account";.
But I strongly believe the problem isn't with my $conn, I could be wrong tho.
There are some problems you should take care about
Try to avoid using global variables inside functions. It may be dangerous in any application because you might change them without wanting it.
Take care of SQL injection. You may consider starting to use prepared statements in order to avoid it.
You are limiting the results to 1 but still use a loop to get the results
You are using mysqli functions but the connection is done using mysql_connect
You didn't select any database to work with, when created the connection
The connection should be done using mysqli_connect:
$mysql = mysqli_connect($host, $user, $password, $databaseName);
You are using mysqli_query but mysql_connect, so use mysqli_connect() and it works
You are mixing mysql and mysqli-functions, and this is known to fail.
Try replace your mysql_connect with mysqli_connect, but be aware it might require other/additional parameters.
Also, you should reconsider your usage of global variables.
I don't know if this will help?
General `mysqli` connection:
----------------------------
$host = 'localhost';
$uname = 'root';
$pwd = 'xxx';
$db = 'xxx';
$conn=new mysqli( $host, $uname, $pwd, $db );
function aggiornamento( $utente=false ){
global $conn;
global $_CONFIG;
if( !isset( $utente ) or empty( $utente ) ) return false;
$sql="select `login`,`dr`,`db`,`id`,`admin_ishop` from `{$_CONFIG['db_account']}`.`account` where `login`=? limit 1;";
$stmt=$conn->prepare( $sql );
$stmt->bind_param( 's', $param );
$param=$utente;
$result=$stmt->execute();
$stmt->bind_result( $login, $dr, $db, $id, $admin_ishop );
$stmt->fetch();
if( $result ){
$_SESSION['IShop_Login'] = $login;
$_SESSION['IShop_DR'] = $dr;
$_SESSION['IShop_DB'] = $db;
$_SESSION['IShop_AID'] = $id;
$_SESSION['IShop_Admin'] = $admin_ishop;
$stmt->close();
return true;
}
$conn->close();
return false;
}
Test
<?php
include __DIR__.'\conn.php';
/*
Where conn.php is simply:
-------------------------
<?php
$host = 'localhost';
$uname = 'root';
$pwd = 'xxx';
$db = 'so_experiments';
$conn = new mysqli( $host, $uname, $pwd, $db );
?>
*/
/* Defined so as not to break sql stmt */
$_CONFIG['db_account']='so_experiments';
function aggiornamento( $utente=false ){
global $conn;
global $_CONFIG;
if( !isset( $utente ) or empty( $utente ) ) return false;
$sql="select `login`,`dr`,`db`,`id`,`admin_ishop` from `{$_CONFIG['db_account']}`.`account` where `login`=? limit 1;";
$stmt=$conn->prepare( $sql );
$stmt->bind_param( 's', $param );
$param=$utente;
$result=$stmt->execute();
$stmt->bind_result( $login, $dr, $db, $id, $admin_ishop );
$stmt->fetch();
if( $result ){
$_SESSION['IShop_Login'] = $login;
$_SESSION['IShop_DR'] = $dr;
$_SESSION['IShop_DB'] = $db;
$_SESSION['IShop_AID'] = $id;
$_SESSION['IShop_Admin'] = $admin_ishop;
/* only for demo debug */
echo 'login:', $login,', db:', $db,', dr:', $dr,', id:', $id,', admin_ishop:', $admin_ishop;
$stmt->close();
return true;
}
$conn->close();
return false;
}
/* call the function with a value for `$utente` = 'default' */
call_user_func( 'aggiornamento', 'default' );
/*
outputs:
login:default, db:store, dr:43, id:1, admin_ishop:1
*/
?>
Try this
<?php
function aggiornamento($utente){
global $conn;
global $_CONFIG;
$selezione = mysqli_query ($conn, "SELECT * FROM ".$_CONFIG['db_account'].".account WHERE login = '".$utente."' LIMIT 1");
while ($row = $selezione->fetch_assoc())
{
$_SESSION['IShop_Login']= $row['login'];
$_SESSION['IShop_DR'] = $row['dr'];
$_SESSION['IShop_DB'] = $row['db'];
$_SESSION['IShop_AID'] = $row['id'];
$_SESSION['IShop_Admin'] = $row['Admin_IShop'];
}
}
?>
I have established a connection with my SQL Database through Windows Authentication in my php file. However I'm not sure how the syntax will look if I wanted to display a simple SQL query such as (Select * from Media) on the php page that shows an entire table. I tried a few methods but it displayed a fatal error.
Here is my code for the php:
<?php
$serverName = "172.20.90.170,5050"; //serverName\instanceName
// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>"TestDB");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$version = mssql_query('SELECT * FROM MEDIA');
$row = mssql_fetch_array($version);
echo $row[0];
?>
Fatal Error:
Fatal error: Call to undefined function mssql_query()
This establishes a succesful connection but what would I need to change in my code for this query to run error free and display the required output?
It appears you are mixing two different API's (sqlsrv_ and mssql_).
If you're using sqlsrv_, then a simple statement could look like:
$connectionInfo = array( "Database" => "database", "UID" => "username", "PWD" => "password" );
$conn = sqlsrv_connect( "Server", $connectionInfo );
$stmt = "SELECT [column] FROM [table] WHERE [id] = ?";
$params = array( $id );
$query = sqlsrv_query( $conn, $stmt, $params );
if( $query === false ) {
print( print_r( sqlsrv_errors() ) );
}
while( $row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC )) {
echo $row['column'];
}
sqlsrv_close( $conn );
Resources
MSDN Documentation
PHP Documentation (contains both Windows & SQL Server authentication examples)
From what I understand, you're new to the PHP world, BUT, I advise you to use the PDO class. You will have more facility to do what you want.
Here's a sample using your data.
If you study, you can understand.
try
{
$connection = new PDO("sqlsrv:Server=172.20.90.170;Database=TestDB", "YOUR_USERNAME", "YOUR_PASSWORD");
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection->setAttribute(PDO::SQLSRV_ATTR_ENCODING, PDO::SQLSRV_ENCODING_SYSTEM);
}catch (Exception $e)
{
echo $e->getMessage();
die('Connection could not be established.<br />');
}
try
{
$sql = 'SELECT * FROM MEDIA';
$query = $connection->prepare($sql);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}catch (Exception $e)
{
die('Cant fetch rows.');
}
foreach ($result as $r)
{
print_r($r); // do what you want here
}
As others says in the comments, you have two options:
1. Use sqlsrv_query
2. Install MSSQL support to PHP.
Sincerely, I prefer use mssql_* stack of functions. If you use ubuntu, you can install MSSQL support simply:
aptitude install php5-sybase
I have data's stored with the delimiter / in my table. I need to separate them and need to store them in different table. While doing that i'm getting:
Notice: Undefined index: VSX1 in /opt/lampp/htdocs/disease.php on line 21
How can I solve this kind of error?
<html>
<body>
<?php
$username = "root";
$password = "****";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("disease",$dbhandle) or die("Could not select disease");
$result = mysql_query("SELECT * FROM `primary_data` LIMIT 0, 30");
while($row = mysql_fetch_array($result))
{
$string = $row['gene_name'];
$tok = strtok($string, "/");
while ($tok !== false) {
mysql_query("insert into temp_gene gene_name values('".$_POST[$tok]."')");
$tok = strtok("/");
}
}
mysql_close($dbhandle);
?>
</table>
</body>
</html>
You transfer data from one table and save it to another. You need no $_POST variable at all!
Of course, data MUST be escaped well.
while (($tok = strtok($string, '/')) !== false) {
$tok = mysql_real_escape_string($tok);
mysql_query("INSERT INTO temp_gene(gene_name) VALUES('{$tok}')");
}
I second Brad:s advice of using PDO & prepared statements - it is way more elegant and efficient.
Here's some code for you... as I have no idea what you want to do with tokensizing, etc. I've not written the logic for what to do with $gene_name, but I'm sure you do =)
Have a look at http://www.php.net/manual/en/book.pdo.php
I also advice you to use Doctrine as a wrapper/ORM on top of PDO, it makes things real easy: http://www.doctrine-project.org/
$dsn = "mysql:dbname={$db_name};host={$db_host}";
try {
// init db handler.
$db = new PDO( $dsn, $db_username, $password );
// Execute selecting query.
$select_sql = "SELECT gene_name FROM `primary_data` LIMIT 0, 30";
$select_stmt = $db -> prepare( $sql );
$select_stmt -> execute();
// Bind row column 1 (1-indexed) to $gene_name.
$select_stmt -> bindColumn( 1, $gene_name );
// Prepare insert query to temp_gene.
$temp_sql = "INSERT INTO temp_gene(gene_name) VALUES(?)";
$temp_stmt = $db -> prepare( $temp_sql );
// Begin transaction, it is more efficient to use transactions as your actual queries becomes 1 instead of O(rows).`enter code here`
$db -> beginTransaction();
while ( $row = $select_stmt -> fetch( PDO::FETCH_BOUND ) ) {
$string =& $gene_name;
// do your tokenizing logic here... also do escaping for security.
$temp_stmt -> execute( array( $your_value_string ) );
}
// Commit the inserts.
$db -> commit();
} catch (PDOException $e) {
die( $e->getMessage() );
}
I'm in the process of learning to use OOP in php, I'm having a few issues with what is probably a really simple solution that I'm just not using the right search terminology to find.
I have my class
class user {
function getUser() {
if ($_SESSION['status'] == "authorized") {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM users WHERE username = :username";
$st = $conn->prepare( $sql );
$st->bindValue( ":username", $_SESSION['usernames'], PDO::PARAM_STR );
$st->execute();
$row = $st->fetch();
$conn = null;
return $row;
}
}
}
and then in my template file i'm calling the following
$user = new user();
echo $user->getUser->icon;
hopefully the bottom line shows what i'm trying to call, basically in the sql results I'm after just calling $row['icon']; directly from the return array.
is this possible? if so could someone point out the terminology i'm missing
Thanks in advance
If you are going to keep using that object I would do the following:
class user {
public $icon;
function getUser() {
if ($_SESSION['status'] == "authorized") {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM users WHERE username = :username";
$st = $conn->prepare( $sql );
$st->bindValue( ":username", $_SESSION['usernames'], PDO::PARAM_STR );
$st->execute();
$row = $st->fetch();
$conn = null;
$this->icon=$row;
}
}
}
Then you can use:
echo $user->icon;
Try the following :
print_r ($user->getUser);
If that returns an array, try it like this :
echo $user->getUser['icon'];
You should use it this way:
$userobj = new User();
$user = $userobj->getUser();
Now you have the fetched data in the $user variable and may output it at will:
echo $user['icon'];
My example should work with your existing code, and if you want to change the values in the future of the users, you just change the key in the echo statement: echo $user['someothervalue'];