mysql_* to MySQLi - php

I recently learned that mysql_* has been depreciated and i have a quick question on how to rewrite something.
$db = mysql_connect("localhost","root","PASSWORD");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("FormData" ,$db);
I have tried rewriting it like this...
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData", $db);
if(!$db) die("Error connecting to MySQL database.");
But when it posts my form i get the "Error connecting to MySQL database." error. I was able to fix it by just using this but i wanted to know how to add in the Error connecting.
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData");
Any help would be great as i try to learn all of the new MySQLi stuff!

PHP website
Straight from php.net
<?php
$mysqli = new mysqli('localhost', 'fake_user', 'my_password', 'my_db');
// Works as of PHP 5.2.9 and 5.3.0.
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
?>
Edit:
The below will also allow you to do it your way.
$mysqli = mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');
Then you can:
if (!$mysqli) {
//handle the error
}
Consider PDO if possible. They are kind similar to me.

$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData", $db);
if(!$db) die("Error connecting to MySQL database.");
should be
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData");
if($mysqli->connect_error) die("Error connecting to MySQL database.");
the parameters for mysqli() are:
[ string $host = ini_get("mysqli.default_host") [, string $username = ini_get("mysqli.default_user") [, string $passwd = ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port = ini_get("mysqli.default_port") [, string $socket = ini_get("mysqli.default_socket") ]]]]]]
Not sure why you were trying to use the $db variable to set the port for the connection and then checking if the port variable is true...
For future reference the best place to look first, would be the docs
EDIT
As #Touch pointed out, you must check if error exists and not just that object exists. Edited code to reflect this.

Using mysqli:
define('DB_HOST', 'localhost');
define('DB_NAME', 'some_database_name');
define('DB_USER', 'some_user');
define('DB_PASS', 'some_password');
$Connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$Connection->connect_errno)
{
//do your prepared stuffs
}
else
{
die("Database Connection error:".$Connection->connect_error);
}
or using PDO
try
{
$PDOConnection = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASS);
$PDOConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//do your prepared stuffs
$PDOConnection = null;
}
catch(PDOException $e)
{
die('ERROR: ' . $e->getMessage());
}

I wrote a class called better_mysqli that extends mysqli making it easier to use.
The following example shows the answer to your question and also shows basic usage of the better_mysqli class. You can view a detailed example with lots of comments here: detailed usage of better_mysqli
<?php
include_once('better_mysqli.php'); // can be obtained from: http://pastebin.com/ATyzLUfK
// THIS NEXT PART ANSWERS YOUR QUESTION
// THIS NEXT PART ANSWERS YOUR QUESTION
// THIS NEXT PART ANSWERS YOUR QUESTION
// THE ONLY DIFFERENCE IN THE CONNECTION WHEN USING better_mysqli AND mysqli
// is $mysqli = new better_mysqli(...) and $mysqli = new mysqli(...)
// == Instantiate the mysqli database object (aka open the database) ==
$mysqli = new better_mysqli('your_server', 'your_user', 'your_pass', 'your_db_name');
if (mysqli_connect_errno()) {
error_log(sprintf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error()));
exit;
}
// == select example ==
unless( $sth = $mysqli->select('select * from table1 where col1=? and col2=?', $row, array('col1_placeholder_value', 'col2_placeholder_value'), $debug_level=0, $verbose_debug_output)){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
while($sth->fetch()){
echo $row['col1'] .', '. $row['col2'] .', and '. $row['col_etc'] .' are accessed like that.<br>';
}
// == insert example ==
$statement = "insert into table1 (col1, col2, date_col, col_etc) values (?, ?, NOW(), ?)";
unless( $mysqli->insert($statement, array('col1_insert_value', 'col2_insert_value', 'col_etc_value'), $debug_level=0, $verbose_debug_output, $id_of_new_record) ){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
// == update example ==
unless($mysqli->update("update table1 set col1=? where col2=?", array('col1_value', 'col2_value'), $debug_level=0, $verbose_debug_output) ){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
// == delete example ==
unless( $mysqli->delete("delete from table1 where col1=? where col2=?", array('col1_value', 'col2_value'), $debug_level=0, $verbose_debug_output) ){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
// in all cases statements are prepared just once and cached so if you reuse any statement the already prepared statement handle is automatically used
?>

Related

MySQL error message, mysql_connect(), any way to fix it?

So this is the error message:
PHP Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
This is the affected piece of code:
class wdClient {
var $dbLink; // The database link
var $prefix; // Table prefix
var $script; // The script running
/**
* Construct a new directory object.
*/
function wdClient() {
error_reporting(E_ALL ^ E_NOTICE);
$this->prefix = WDDBPREFIX;
// Connect to the database
$this->dbLink = mysql_connect(WDDBHOST, WDDBUSER, WDDBPASSWD);
// Select the database
mysql_select_db(WDDBNAME, $this->dbLink) or die('Sorry, The site is currently unavailable!');
}
where WDDBPREFIX, WDDBHOST, WDDBUSER, WDDBPASSWD, WDDBNAME are already defined in a config file.
I have tried simply using mysqli_connect instead of mysql_connect but it's not working.
Note: Never use MySQL, use this method!
//MySQLi information
$db_host = "localhost";
$db_username = "username";
$db_password = "password";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());
Good luck!
well, as pointed in here http://php.net/manual/en/function.mysqli-connect.php , you should make something like this:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
Apparently, in your case it will look like this:
$link = mysqli_connect(WDDBHOST, WDDBUSER, WDDBPASSWD, WDDBNAME);
And then you can continue with your code...
if (!link){
die('Sorry, The site is currently unavailable!');
} else{
// write your SQL here and fetch it
}

why mysqli_connect() returning true even I passing wrong username?

Here's my code.
<?php
$server = "localhost";
$uname = "replace it with anything";
$pswd = "";
$conn = mysqli_connect($server, $uname, $pswd);
if(!$conn){
die('Caught');
}
else{
die('Connected');
}
?>
No matter what I passed in the mysqli_connect() as username. It always returns true. In the case of the wrong password, it shows an error that accesses denied, but I don't know why, no matter what I enter in the username, it always returning true.
It does not return a boolean but an object which represents the connection. You can then check the object for connectivity. From the manual:
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
Try
<?php
$mysqli = new mysqli("host", "username", "password", "database") or die($mysqli->error());
if ($mysqli->connect_errno) {
echo "error";
exit();
}
?>

Error! Call to undefined function pg_insert()

I am trying to copy an array into a table in the test database. I get this fatal error: Call to undefined function pg_insert() in C:\wamp\www\Lessons\GMS-DB.php on line 31. Can u please help me!
Here is my code:
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$database = "test";
// Create server connection
$con = mysql_connect ($servername, $username, $password, $database) or die('cant connect server');
mysql_select_db('test',$con);
// Create database connection
$db_selected = mysql_select_db('test',$con);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
//-----------------------------------------------------------------------
// Specify directory
$dir = 'C:/Users/Desktop/data';
$files1 = scandir($dir);
$data = array_diff($files1, array('.', '..')); //remove the dots or periods
// print_r($data);
// put in a string
$matstring = implode("','",$data);
$matstring="".$matstring."";
$table_name = `test table 1`;
$res = pg_insert ($con , $table_name , $data);
if ($res) {
echo "POST data is successfully logged\n";
} else {
echo "User must have sent wrong inputs\n";
}
?>
You have two different kinds of databases there. One is MySQL and another is PostgreSQL. Your using a mysql database so use a mysql query to insert.
You need to use mysql query
mysql_query("INSERT INTO $table (column_name, column_name2) VALUES('$value', '$value2')");
Also, you are using mysqli syntax to connect to db. In mysql, the syntax is
$con = mysql_connect ($servername, $username, $password);
mysql_select_db('foo', $con);
And I strongly suggest you to use mysqli. Ancient mysql is no longer supported!
Here's the code in MySQLi
$db = new mysqli("host", "user", "password", "database");
$db->query("INSERT INTO $table (column_name, column_name2) VALUES('$value', '$value2')");
When should I use MySQLi instead of MySQL?
MySQLi Query

Can i use multiple databases in one applicationin php?

I am Developing the simple application,the application related to database operations.
My doubt is how can i connect to multiple databases same time.
how can php knows which databases the data will store.
If the user enter the data which database it will enter,both databases or one database.
Please answer my question.i have struggling a lot for this question.
If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.
You would connect through PDO, like this:
try {
$db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
(Of course replace databasename, username and password above)
You can then query the database like this:
$result = $db->query("select * from tablename");
foreach ($result as $row) {
echo $row['foo'] . "\n";
}
Or, if you have variables:
$stmt = $db->prepare("select * from tablename where id = :id");
$stmt->execute(array(':id' => 42));
$row = $stmt->fetch();
If you need multiple connections open at once, you can simply create multiple instances of PDO:
try {
$db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
$db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
Yes you can.. by using two connection strings..
$mysqli1 = new mysqli('HOST1', 'USER1', 'PASSWORD1', 'DB_NAME1');
$mysqli2 = new mysqli('HOST2', 'USER2', 'PASSWORD2', 'DB_NAME2');
and your queries should be like
$result1 = $mysqli1->query('query ......');
and
$result2 = $mysqli2->query('query ......');
Of course you can given example below add more connections if you want:
Class database
{
private oracleDatabase;
private mysqlDatabase;
public function connOracle() {
$db = "";
$user = "";
$password = "";
try {
$this->oracleDatabase = new PDO("oci:dbname=".$db,$user,$password);
} catch(PDOException $e){
echo "Can't connect to database (Oracle). ". $e->getMessage();
}
}
public function connMysql() {
$db = "";
$user = "";
$password = "";
try {
$this->mysqlDatabase = new PDO("mysql:dbname=".$db,$user,$password);
} catch(PDOException $e){
echo "Can't connect to database (Mysql). ". $e->getMessage();
}
}
}
Be carefull if you are using two databases on the same server at the same time. By default mysql_connect returns the same connection ID for multiple calls with the same server parameters, which means if you do
<?php
$db1 = mysql_connect(...stuff...);
$db2 = mysql_connect(...stuff...);
mysql_select_db('db1', $db1);
mysql_select_db('db2', $db2);
?>
then $db1 will actually have selected the database 'db2', because the second call to mysql_connect just returned the already opened connection ID !
You have two options here, eiher you have to call mysql_select_db before each query you do, or if you're using php4.2+ there is a parameter to mysql_connect to force the creation of a new link.
Use this below link to refer.What you have asked here.
PHP Documentation
Yes, you may use multiple database in one application, but the main thing is when you are communicating with the dbname, you have to specify that dbname also so than script will communicate with only that db in which you had defined. Ex.
$db1 = mysql_connect(...stuff...);
$db2 = mysql_connect(...stuff...);
mysql_select_db('db1', $db1);
mysql_select_db('db2', $db2);
$resultsa = mysql_query('SELECT * FROM table_a', $dbname) or die('Could not query database_a');
Yes you can connect multiple databases.
open your php.ini file and give me your database details like
port number,username,password.
And after that you can give the queries like this in your applications
$db1 = mysql_connect($hostname, $username, $password);
$db2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $db1);
mysql_select_db('database2', $db2);
Then to query database 1, do this:
mysql_query('select * from tablename', $dbh1);
and for database 2:
mysql_query('select * from tablename', $dbh2);
i think this is work fine for your question.
Yes you can, in very basic terms, you do it like this:
http://au1.php.net/function.mysql-connect
$conn = mysql_open($host, $username, $password, true);
To connect to multiple databases on the same server:
$dblink1 = mysql_select_db('database_a', $conn);
$dblink2 = mysql_select_db('database_b', $conn);
To get results from two databases:
$resultsa = mysql_query('SELECT * FROM table_a', $dblink1) or die('Could not query database_a');
$resultsb = mysql_query('SELECT * FROM table_b', $dblink2) or die('Could not query database_b');
edit - keep in mind that the mysql_ functions aren't available in recent PHP releases because they've been removed.
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information.

Cloud SQL using mysqli error

I'm trying to output the results of a simple query using a Google Cloud SQL with a mysqli connection. I've properly set up a Cloud SQL instance and imported a SQL database. However, when I run my app, it seems to connect to the database - no errors are triggered there - but the logs show the following:
PHP Fatal error: Wrong SQL: SELECT * FROM students Error: No database selected in /base/data/home/apps/s~db-php-001/1.371796924944999585/main.php on line 18
Here's my code:
$conn = new mysqli(null,"root","",null,null,"/cloudsql/db-php-001:db-instance-001");
// check connection
if($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$sql='SELECT * FROM students';
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$rows_returned = $rs->num_rows;
}
Obviously, I'm triggering that error, but I'm can't figure out why. There is definitely a table named students in the database.
Anyone have any ideas?
Thanks!! Joe
You've set your database name to null. A connection is made like so:
$mysqli = new mysqli("localhost", "user", "password", "database");
The mysqli constructor can take in the following parameters (in this order):
$mysqli = mysqli($hostname, $username, $password, $database, $port, $socket);
In your case, you've set the parameters to be:
$hostname = null; //Defaults to mysqli.default_host
$username = "root";
$password = "";
$database = null; //Defaults to ""
$port = null; //Defaults to mysqli.default_port
$socket = "/cloudsql/db-php-001:db-instance-001";
To clarify, you can pass null for the database name. In the query you'd need to use the fully qualified table name (<database>.Students in your case). Or you can use the mysqli_select_db() function to select the database to use.

Categories