I am new to mysqli and was going through a tutorial from: http://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17#comment1
I was able to connect to my database using this:
$config = parse_ini_file('../config.ini');
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if($connection === false) {
die('Connection failed [' . $db->connect_error . ']');
}
echo("hello"); //this worked!
But then I tried wrapping it in a function (as discussed in the tutorial)... I saw that you call the connection function from another function... in the tutorial each function keeps getting called from another and another... and I never quite found where the initial call started from to get the domino effect of functions calling eachother.. so anyway, I tried to stop it at two just to test and teach myself.. but it's not working and I don't know why:
function db_connect() {
static $connection;
if(!isset($connection)) {
$config = parse_ini_file('../config.ini');
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
echo("hello2");
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
echo("hello1");
}
db_query("SELECT `Q1_Q`,`Q1_AnsA` FROM `Game1_RollarCoaster`"); //this didn't work :(
Well I ended up taking it out of the functions and made the code super simple (sticking with procedural instead of OOP even though a lot of tutorials use OOP - thought it was better to start this way):
<?php
$config = parse_ini_file('../config.ini');
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_Q] . '<-- Here is your question! ' . $row[Q1_AnsA] . '<-- Here is your answer! ';
echo '<br />';
}
mysqli_free_result($result);
mysqli_close($link);
?>
Here's a simple mysqli solution for you:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
$row = $resource->fetch_assoc();
echo "{$row['field']}";
$resource->free();
$db->close();
If you're grabbing more than one row, I do it like this:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With Error Handling: If there is a fatal error the script will terminate with an error message.
// ini_set('display_errors',1); // Uncomment to show errors to the end user.
if ( $db->connect_errno ) die("Database Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) die('Database Error: '.$db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With try/catch exception handling: This lets you deal with any errors all in one place and possibly continue execution when something fails, if that's desired.
try {
if ( $db->connect_errno ) throw new Exception("Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) throw new Exception($db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
} catch (Exception $e) {
echo "DB Exception: ",$e->getMessage(),"\n";
}
Related
I am pretty new to PHP, I have referred some examples and made a code for getting data from database. but if the database is not found I am getting a text response , Can anyone suggest how to get a proper JSON response back if no database found or misconfigured
This is my $http.get method
$http.get('client/php/popData.php')
.success(function(data) {
$scope.blogs = data;
})
.error(function(err) {
$log.error(err);
})
popdata.php for getting data from database
<?php
$data = json_decode(file_get_contents("php://input"));
include('config.php');
$db = new DB();
$data = $db->qryFire();
echo json_encode($data);
?>
This is my config.php
<?php
define("__HOST__", "localhost");
define("__USER__", "username");
define("__PASS__", "password");
define("__BASE__", "databasename");
class DB {
private $con = false;
private $data = array();
public function __construct() {
$this->con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__);
if(mysqli_connect_errno()) {
die("DB connection failed:" . mysqli_connect_error());
}
}
public function qryPop() {
$sql = "SELECT * FROM `base` ORDER BY `id` DESC";
$qry = $this->con->query($sql);
if($qry->num_rows > 0) {
while($row = $qry->fetch_object()) {
$this->data[] = $row;
}
} else {
$this->data[] = null;
}
$this->con->close();
}
public function qryFire($sql=null) {
if($sql == null) {
$this->qryPop();
} else {
$this->con->query($sql);
$this->qryPop();
}
// $this->con->close();
return $this->data;
}
}
?>
Use Exceptions:
Change your class DB like this:
public function __construct() {
$this->con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__);
if(mysqli_connect_errno()) {
throw new Exception("DB connection failed:" . mysqli_connect_error());
}
}
Then change your popdata.php like
<?php
$data = json_decode(file_get_contents("php://input"));
include('config.php');
try {
$db = new DB();
$data = $db->qryFire();
} catch (Exception $e) {
echo json_encode(['error' => $e->getMessage()]);
exit();
}
echo json_encode($data);
This way you will get error response in JSON for any Exception thrown while constructing the DB class and while executing DB::qryFire
if you want to catch your warnings you can try modifying your DB class like the below:
public function __construct() {
ob_start();
$this->con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__);
$warning = ob_clean();
if ($warning) {
throw new Exception($warning);
}
if(mysqli_connect_errno()) {
throw new Exception("DB connection failed:" . mysqli_connect_error());
}
}
You can also turn off your warnings and notices by adding
error_reporting(E_ERROR);
on the top of your file
replace the line die("DB connection failed:" . mysqli_connect_error()); in DB class __construct function with
die( json_encode( array('status' => 'error') ) );
when ever the app will fail to connect to the data base it will give
{"status": "error"}
i did not checked this. but i hope it will work
btw it's my 1st answer on stackoverflow. i'm sorry for my mistakes. correct them
I'm new to php. I have this piece of code:
<?php
if (!isset($_GET['id'])) {
die("missing query parameter");
}
$id = intval($_GET['id']);
if ($id === '') {
die("Invalid query parameter");
}
$db = mysql_connect("localhost", "root", "usbw");
$sdb = mysql_select_db("test", $db);
$sql = "SELECT * FROM config WHERE id=$id";
$mq = mysql_query($sql) or die("not working query");
$row = mysql_fetch_array($mq);
?>
And from this code, I want to make a function, but how?
What I'm trying to do is linking my MySQL database to my PHP code, and I also try to use the GET[id] to auto change my page if a change my id.
This piece of code does work, but I want to change it into a function. But I don't know how to start.
Here's an example of a function around your query, mind you it's just an example, as there are many improvements to make.
Such as not using the mysql_* api and moving towards PDO or mysqli_*
But it should be enough to get you started
<?php
// your if logic stays unchanged
$db=mysql_connect("localhost","root","usbw");
$sdb=mysql_select_db("test",$db);
function getConfig($id,$db){
$sql="SELECT * FROM config WHERE id=$id";
$mq=mysql_query($sql);
if ($mq) {
return mysql_fetch_array($mq);
}
else {
return false;
}
}
$results = getConfig($id,$db);
if ($results==false) {
print "the query failed";
}
else var_dump($results);
You can make a file named db.php including some common db functions so you will be able to use them easier:
<?php
function db_connection() {
//SERVER, USER, MY_PASSWORD, MY_DATABASE are constants
$connection = mysqli_connect(SERVER, USER, MY_PASSWORD, MY_DATABASE);
mysqli_set_charset($connection, 'utf8');
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
return $connection;
}
function db_selection() {
$db_select = mysqli_select_db(MY_DATABASE, db_connection());
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
return $db_select;
}
function confirm_query($connection, $result_set) {
if (!$result_set) {
die("Database error: " . mysqli_error($connection));
}
}
function q($connection, $query) {
$result = mysqli_query($connection, $query);
confirm_query($connection, $result);
return $result;
}
?>
Then, you can have your code in some other files:
<?php
require_once('db.php'); //This file is required
$id = $_GET['id']; //Shorthand the $_GET['id'] variable
if (!isset($id)) {
die("missing query parameter");
}
if ( filter_var($id, FILTER_VALIDATE_INT) === false) ) {
die("Invalid query parameter");
}
$sql = "SELECT * FROM config WHERE id = '$id'";
$result = q($connection, $sql);
while ($row = mysqli_fetch_array($result)) {
//Do something
}
?>
Try not to use mysql_* functions because they are deprecated. Use mysqli_* or even better try to learn about prepared statements or PDO.
I have this script that deletes a certain picture from the website. It's written with mysql functions so i wanted to update it to mysqli but doing so makes the script stop working. No die message from the script are shown no php errors and adding error_reporting(E_ALL); doesn't show any errors either.
Original script:
if(isset($_POST['F3Verwijderen']))
try
{
//delete the file
$sql = "SELECT PandFoto3 FROM tblpand WHERE `PK_Pand` = '".$pandid."'";
$con = mysql_connect('WEBSITE.mysql', 'WEBSITE', 'PASS');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("WEBSITE");
$result = mysql_query($sql, $con);
while ($row = mysql_fetch_array($result)) {
if(file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3'])) {
unlink($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3']);
} else {
echo $row['PandFoto3'];
}
}
//delete the path url from the database field
mysql_query("UPDATE tblpand SET PandFoto3 = NULL WHERE `PK_Pand` = '".$pandid."'");
mysql_close($con);
header('Location: ../admin/pand-aanpassen.php?id='.$pandid);
}
Updated to mysqli:
try
{
//delete the file
$sql = "SELECT PandFoto3 FROM tblpand WHERE `PK_Pand` = '".$pandid."'";
$con = mysqli_connect('WEBSITE.mysql', 'WEBSITE', 'PASS');
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db("WEBSITE");
$result = mysqli_query($sql, $con);
while ($row = mysqli_fetch_array($result)) {
if(file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3'])) {
unlink($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3']);
} else {
echo $row['PandFoto3'];
}
}
//delete the path url from the database field
mysqli_query("UPDATE tblpand SET PandFoto3 = NULL WHERE `PK_Pand` = '".$pandid."'");
mysqli_close($con);
header('Location: ../admin/pand-aanpassen.php?id='.$pandid);
}
Edit:
"no php errors and adding error_reporting(E_ALL); doesn't show any errors either."
That's because it isn't a PHP issue, it's a MySQL issue.
Those are two different animals altogether.
As I said in commments, you need to switch these variables ($sql, $con) around ($con, $sql).
Then this:
$con = mysqli_connect('WEBSITE.mysql', 'WEBSITE', 'PASS');
Just use the 4th parameter instead of mysqli_select_db("WEBSITE"); where you didn't pass the connection variable to.
$con = mysqli_connect('WEBSITE.mysql', 'WEBSITE', 'PASS', 'WEBSITE');
The syntax is:
host
username
password (if any)
database
You also could have done mysqli_select_db($con, "WEBSITE");
Sidenote: In mysql_ (see footnotes), the connection comes last, unlike in mysqli_ which comes first.
Do the same for your UPDATE and pass the connection parameter first.
mysqli_query($con, "UPDATE...
Sidenote: To verify that the update truly was successful, use affected_rows()
http://php.net/manual/en/mysqli.affected-rows.php.
Another thing, mysqli_error() requires a connection to it mysqli_error($con) and check for errors for your queries.
I.e.:
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
References:
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.select-db.php
Sidenote:
You're using try() but no catch(). Either remove it, or consult the manual:
http://php.net/manual/en/language.exceptions.php
Example #4 pulled from the manual:
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}
try {
echo inverse(5) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "First finally.\n";
}
try {
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "Second finally.\n";
}
// Continue execution
echo "Hello World\n";
?>
Final notes:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
Footnotes: (MySQL and MySQLi comparison)
In regards to mysql_query():
mixed mysql_query ( string $query [, resource $link_identifier = NULL ]
http://php.net/manual/en/function.mysql-query.php
For mysqli_query():
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
http://php.net/manual/en/mysqli.query.php
I have a while loop inside a foreach loop. The while loop never exits and crashes the server, I can't figure out why. Here's a condensed version of the code.
foreach( $final_plates as $key => $value) {
$Plate_No = ($value['plate_no']);
$sql = "SELECT J.PLATE_NO FROM PLATE_LOGS J WHERE (J.PLATE_NO = " . $Plate_No . ")";
$db->query($sql);
while ($row = oci_fetch_assoc($db2->result)) {
echo $row['PLATE_NO'] . "</br>";
}
}
If I use the following statement instead of the while loop, the first record will be found without any problem
$row = oci_fetch_assoc($db->result);
I am using a class to connect to the database that I didn't write. I'm also new to programming. Here's some code from the class.
function connect(){
$this->connection = oci_connect($this->user, $this->password, $this->db) or die("Connection Failed: " . oci_error());
if(!$this->connection)
{
return false;
}
}
function query($sql){
// Query SQL
$this->result = oci_parse($this->connection, $sql) or die ("SQL ERROR" . oci_error($this->connection));
oci_execute($this->result) or die ("SQL ERROR" . oci_error($this->result));
}
I was wondering if there's a way in PHP to list all available databases by usage of mysqli. The following works smooth in MySQL (see php docs):
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
}
Can I Change:
$db_list = mysql_list_dbs($link); // mysql
Into something like:
$db_list = mysqli_list_dbs($link); // mysqli
If this is not working, would it be possible to convert a created mysqli connection into a regular mysql and continue fetching/querying on the new converted connection?
It doesn't appear as though there's a function available to do this, but you can execute a show databases; query and the rows returned will be the databases available.
EXAMPLE:
Replace this:
$db_list = mysql_list_dbs($link); //mysql
With this:
$db_list = mysqli_query($link, "SHOW DATABASES"); //mysqli
I realize this is an old thread but, searching the 'net still doesn't seem to help. Here's my solution;
$sql="SHOW DATABASES";
$link = mysqli_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql: ' . mysqli_error($link).'\r\n');
if (!($result=mysqli_query($link,$sql))) {
printf("Error: %s\n", mysqli_error($link));
}
while( $row = mysqli_fetch_row( $result ) ){
if (($row[0]!="information_schema") && ($row[0]!="mysql")) {
echo $row[0]."\r\n";
}
}
Similar to Rick's answer, but this is the way to do it if you prefer to use mysqli in object-orientated fashion:
$mysqli = ... // This object is my equivalent of Rick's $link object.
$sql = "SHOW DATABASES";
$result = $mysqli->query($sql);
if ($result === false) {
throw new Exception("Could not execute query: " . $mysqli->error);
}
$db_names = array();
while($row = $result->fetch_array(MYSQLI_NUM)) { // for each row of the resultset
$db_names[] = $row[0]; // Add db name to $db_names array
}
echo "Database names: " . PHP_EOL . print_r($db_names, TRUE); // display array
Here is a complete and extended solution for the answer, there are some databases that you do not need to read because those databases are system databases and we do not want them to appear on our result set, these system databases differ by the setup you have in your SQL so this solution will help in any kind of situations.
first you have to make database connection in OOP
//error reporting Procedural way
//mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//error reporting OOP way
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL & MYSQLI_REPORT_STRICT;
$conn = new mysqli("localhost","root","kasun12345");
using Index array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_NUM)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row[0] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row[0];
}
}
same with Assoc array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row["Database"] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row["Database"];
}
}
same using object of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($obj = $result->fetch_object()){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if( $obj->Database == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'. $obj->Database;
}
}