php - blank page when using code to connect to data base - php

i get a blank page when using code to connect to a database using php
even any print statement out side of the connection code is not printed only a blank page when running the following code
<?php
$link = new mysqli('localhost', 'root', '7610', 'sites');
if ($link) {
print "connected";
}
else { print "faild";}
?>

Try to use mysqli_connect() instead of mysqli()

Most People agree that PDO offers so much advantages over mysqli functions.... Why not try that Route? You would be glad you did... Here's what a PDO-based version would look like....
<?php
//DATABASE CONNECTION CONFIGURATION:
defined("HOST") or define("HOST", "localhost"); //REPLACE WITH YOUR DB-HOST
defined("DBASE") or define("DBASE", "sites"); //REPLACE WITH YOUR DB NAME
defined("USER") or define("USER", "root"); //REPLACE WITH YOUR DB-USER
defined("PASS") or define("PASS", "7610"); //REPLACE WITH YOUR DB-PASS
try {
$dbh = new PDO('mysql:host='.HOST.';dbname='. DBASE,USER,PASS);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo $e->getMessage();
}
if($dbh instanceof PDO){
print "The Coast is clear...";
}else{
print "We have a Huge Storm on our hands.... BAIL ;-)";
}
// FROM HERE ON, YOU COULD START USING $dbh AS YOUR PDO OBJECT...
// FOR EXAMPLE YOU COULD DO A SELECT LIKE SO:
$sql = 'SELECT u.* FROM user AS u';
$stmt = $dbh->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
var_dump($result);

Related

Null response from server in Php

I'm coding a web service for iOS in Php. I'm trying to retrieve data from server through php but the response is null.The server is MSSql Server 2014.
<?php
define ('DB_HOST', '****.net');
define ('DB_USER', '****');
define ('DB_PASS', '******');
define ('DB_NAME', '*******');
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME, $dbc);
if (mysql_select_db){
echo "Done";
}else{
echo "Die";
}
$sql_select = "SELECT * from ClientChk";
$records = mysql_query($sql_select);
$count= 1;
while($result = mysql_fetch_array($records))
{
if ($result == nil){
echo "Nil!";
}
}
echo json_encode($result['Id']);
?>
This is a bad example of doing this.
1) You have to check if the connection was successful.
2) If use MSSQL, then you can't use mysql_ commands.
3) nill doesn't exist in php, should be 'null'
$SERVER = '127.0.0.1';
$DB = 'test';
$USER = 'username';
$PASSWORD = 'password';
$db = new PDO("sqlsrv:server=$SERVER;database=$DB;", $USER, $PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$query = "SELECT * FROM ClientChk";
$result = $db->query($query)->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $ex) {
$ex->getMessage();
echo $ex;
}
echo json_encode($result);
So, the problem is, that you try to connect to a MSSQL database, with a MySQL database connector.
To connect to a MSSQL database, you can use the following methods:
mssql_connect(): It uses a quite similar syntax to mysql, but it is removed as of php 7.0, so I advice against it's usage even if you using an earlier version of php.
PDO class: It's differs a lot from the older function style sql connectors, but it is the preferred way by many.
sqlsvr_connect(), obdc_connect(): If you prefer a function based connector instead of the PDO class, and you don't want to use the deprecated mssql_connect, I recommend choosing one of these.
I hope, I could be of any help.

How to fix server error 500 when executing PHP script?

I am trying to insert into a database through PHP. However, when I connect to the PHP file I get server 500 error. Would anyone be able to spot what I am doing wrong?
<?php
include 'db-security.php';
function db_login()
{
$userName = filter_input(INPUT_POST, "userName");
$password = filter_input(INPUT_POST, "password");
//binding the variable to sql.
$statement = $link->prepare("INSERT INTO user(username, password)
VALUES($userName, $password)");
//execute the sql statement.
$statement->execute();
}
db_login();
?>
Updated:
I have discovered the error occurs when i add filer_input or $_post to the php.
<?php
include 'db-security.php';
function db_login() {
global $conn;
// use my eaxmple to filter input to get the data out of the form, because security.
//$userName = filter_input(INPUT_POST, "userName");
$userName = $_POST['userName'];
$password = $_POST['password'];
//$password = filter_input(INPUT_POST, "password");
//binding the variable to sql.
$stmt = $conn->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
$stmt->bindParam(':pswd', $password);
$stmt->bindParam(':usrname', $userName);
$stmt->execute();
//execute the sql statement.
}
db_login();
?>
db-security.php
<?php
include_once 'conf.php';
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $conn;
// Try and connect to the database, if a connection has not been established yet
if(!isset($conn)) {
// Load configuration as an array. Use the actual location of your configuration file
try
{
$conn = new PDO("mysql:host=localhost;port=3307;dbname=database", DB_USERNAME,DB_PASSWORD);
// stores the outcome of the connection into a class variable
$db_msg = 'Connected to database';
}
catch(PDOException $e)
{
$conn = -1;
$db_msg = $e->getMessage();
}
//$conn = new PDO(DB_HOST,DB_USERNAME,DB_PASSWORD , MAIN_DB);
}
}
db_connect();
?>
Where is $link defined? In 'db-security.php'? If yes then you have a variable scope problem. Just pass $link in the function call. This would have to be done for all functions.
define function as = function db_login($link)
call function like = db_login($link);
EDIT:
Don't use a function for 'db-security.php' it should be like this:
<?php
$conn = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>
This is not complete code, just a sample. Now $conn is in the global variable scope and using global in the functions will work. Or just pass $conn to the function and not use global at all.
EDIT2:
Below are the working sample scripts. You need to change some information to match your setup. I'm not sure why the function is called db_login() since the function actually adds the user/password into the 'user' table.
conf.php
<?php
define('DB_USERNAME', 'test');
define('DB_PASSWORD', '123456');
?>
db-security.php
<?php
include_once 'conf.php';
try
{
$conn = new pdo("mysql:host=localhost; dbname=test; charset=utf8", DB_USERNAME, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
die('Unable to connect to database!');
}
?>
main script
<?php
include 'db-security.php';
function db_login()
{
global $conn;
$userName = $_POST['userName'];
$password = $_POST['password'];
$stmt = $conn->prepare("INSERT INTO user(username, password) VALUES(:usrname, :pswd)");
$stmt->bindParam(':usrname', $userName);
$stmt->bindParam(':pswd', $password);
$stmt->execute();
}
db_login();
?>
So you need to bind your parameters after prepare statement
$stmt = $link->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
$stmt->bindParam(':pswd', $password);
$stmt->bindParam(':usrname', $userName);
$stmt->execute();
I have been looking at your code and I would advice you to try a different approach. I've been wrapping my head around this subject for a while when learning PHP. Best advice i've had is that you can best try when fetching information from the DB is using a try/catch statement everytime. Sounds annoying or problematic but it easy to overlook and well written maintained code because you know every try catch block will execute or catch the error atleast.
With PDO being one of the best solutions because it can connect with multiple databases the best way to execute getting information from the Database is this:*
I am gonna give you my example of something i wrote. I don't want to write it all out in your situation because i feel that's something you can better do to learn what went wrong and i hope this gives you a step in the right direction.
database.php
$serverName = "";
$dbName = "";
$userName = "";
$password = "";
try {
$db = new PDO("mysql:host=$serverName;dbname=$dbName", $userName, $password);
// Set the PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
}
catch(PDOException $e){
echo"Connection failed: " . $e->getMessage();
exit;
}
?>
index.php Executing a simple commmand get firstName from employers
<?php
require_once 'database.php';
try
{
$sQuery = "
SELECT
firstName
FROM
employees
";
$oStmt = $db->prepare($sQuery);
$oStmt->execute();
while($aRow = $oStmt->fetch(PDO::FETCH_ASSOC))
{
echo $aRow['firstName'].'<br />';
}
}
catch(PDOException $e)
{
$sMsg = '<p>
Regelnummer: '.$e->getLine().'<br />
Bestand: '.$e->getFile().'<br />
Foutmelding: '.$e->getMessage().'
</p>';
trigger_error($sMsg);
}
?>
Good luck and i hope my index.php is helpful in showing you how I find is the best way momentarily to talk to the database.

PDO does not return error even when setting error mode

EDIT: The problem is that the errors are not being displayed. This is just to clarify everyting.
I just learned what a PDO is, and I decided to test how it works. From the tutorials I've checked, you have to use the following line to display errors: $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
So anyways, I used this line, made sure that my query had an error and it still didn't display any errors. The connection to the database works, it always returned me an error when it couldn't connect. Anyways, here my code:
<?php
// Connection to the mysql database using PDO
$mysql_host = "hidden";
$mysql_dbname = "hidden";
$mysql_username = "hidden";
$mysql_password = "hidden";
try {
$DBH = new PDO("mysql:host=$mysql_host;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->prepare("SELECT username FROM username");
} catch (PDOException $e) {
echo "Error connecting to the database:" . $e->getMessage();
}
?>
You don't get any errors because
$DBH->prepare("DELETE use FROM blob");
doesn't execute, only prepares a query to be executed.
Replace that line of code with:
$stmt = $DBH->prepare("DELETE use FROM blob");
$stmt->execute();
You need to execute it
$stmt = $DBH->prepare("DELETE use FROM blob");
$stmt->execute();
Otherwise it doesn't actually run the 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.

Can't connect to database through PHP PDO class

I'm trying to connect to my mySQL database using the PDO class in PHP.
Here is my Code :
// Connects to Our Database via PDO.
if($local) {
try {
$db = new PDO("mysql:=localhost;dbname=bbc_archive;port=3306", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch(Exception $e) {
echo "Connection to the DataBase was not possible. ";
die();
}
} else {
try {
$db = new PDO("mysql:=bbcarchive.db.11505263.hostedresource.com;dbname=bbcarchive", "bbcarchive", "myPassword");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch(Exception $e) {
echo "Connection to the live DataBase was not possible. ";
die();
}
}
The $local variable is defined before and determines whether or not the script is running on a the live server or a test server.
When running in my local environment everthing works fine but on my live server it echo's out "Connection to the live DataBase was not possible." from the catch block.
I've contacted my host provider (godaddy) and they think it's a coding error. I've also, obviously, checked the hostname, dbname, username and password a 100 times and it's all correct. I just can't see the problem!
How can i do this ?
Your DSN seems to be incorrect. The documentation on MySQL DSNs indicates that it should look somewhat like this:
$db = new PDO("mysql:host=localhost;dbname=bbc_archive;port=3306", "root", "");

Categories