MySQL PHP database connection - php

Here is my index.html file. I load the page and nothing happens. Shouldn't it print "Please try again" on the webpage if my info is incorrect?
<html>
<body>
<h1>mySQL</h1>
<?php
$server = "mysql.blah.com";
$username = "my_username";
$password = "my_password";
$database = "my_database";
$mysqlConnection = mysql_connect($server, $username, $password);
if (!$mysqlConnection){
echo "Please try later.";
}
else {
echo "All good";
mysql_select_db($database, $mysqlConnection);
}
?>
</body>
</html>

This is because your file has the .html extension.
Change it to .php and run it again.
Be sure to run it on a web server, that has PHP installed

change the file to the .php extension and use this refactored version
<html>
<body>
<h1>mySQL</h1>
<?php
try
{
$server = "mysql.blah.com";
$username = "my_username";
$password = "my_password";
$database = "my_database";
$mysqlConnection = new PDO('mysql:host={$server};dbname={$database};', '{$username}', '{$password}');
$mysqlConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo ('Please try later.');
echo $e->getMessage();
}
?>
</body>
</html>

Related

Connection to remote MS SQL database from Linux server using PHP

I have hosted my website on Linux server and I want to connect MS SQL database. i have used PHP in programming. I have contacted to both server provider and they helped in their extent. But my issue is not solved Can you guide me what to do. My code is below.
While I run this it is showing " could not find driver1"
Please guide me. Thanks in advance
<?php
//echo phpinfo();
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>testing</h1>
</body>
</html>
<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = 'server:port';
$myDB = "DatabaseName";
// Connect to MSSQL
$link = mssql_connect($server, 'username', 'password');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
else
{
echo "success";
}
?>
<?php
try {
$conn = new PDO("sqlsrv:Server='server_name';Database=database_name", 'username', 'password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
die(print_r($e->getMessage() ));
}
$tsql = "select * from table_name";
$getResults = $conn->prepare($tsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach ($results as $row) {
echo $row['0'].' '.$row['6'];
echo "<br>";
}
?>

Could not connect to MySQL in PHP

I have newly purchased server, on that server database connections are not working.
<?php
error_reporting(E_ALL);
$server = "server name";
$user = "username";
$password = "password";
$db = "test";
echo "Before";
$con = mysql_connect($server, $user, $password);
echo "After";
if (!$con){
die('Could not connect:' . mysql_error());
}
mysql_select_db($db, $con);
?>
When run this file its print Before text but not print After text.
Currently you can use the following code:
ini_set("error_reporting", E_ALL & ~E_DEPRECATED);
Using this you can get either deprecated or not.
FYI: The mysql_* functions have been removed in PHP7.x. There are two modules you can use.
The first is MySQLi, just use the code as follows:
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
You can also use PDO using code :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

How to connect to heroku postgres database?

I'm trying to connect to postgres databse on heroku but it doesn't work for me.
This is the code in index.php
<?php
$host = "my host";
$dbname = "my database name";
$user = "my username";
$password = "my password";
$port = "5432";
$dsn = "pgsql:host=$host;dbname=$dbname;user=$user;port=$port;password=$password";
$db = new PDO($dsn);
if($db){
echo "Connected <br />".$db;
}else {
echo "Not connected";
}
?>
But nothing appear on the screen it should print not connected if the credentials are wrong.
Help Please
Thanks all
You need to get your DATABASE_URL variable. You can get it going here and press 'View Credentials'. Then fill your DB connection with the info provided.
Regards
Try next code, it works with me.
<?php
$con = "dbname=fgsfg10pdq host=ghfghfh4654.amazonaws.com port=5432 user=gafasduyiu password=435346af8493196 sslmode=require";
if (!$con)
{
echo "Database connection failed.";
}
else
{
echo "Database connection success.";
}
?>

Having trouble while receiving data in database

I am trying trying to receive data by making a html form and then adding receiving data by $_GET method.Whenever I try to submit my data I get an error saying 'Your file was not found' in my chrome browser,so I tried opening my php page in chrome by typing "localhost/...." in my address bar and there it was displaying 'Database NOT Found'
here is my php code:-
<html>
<?php
$user_name = "root";
$password = "";
$database = "mysql"; //mysql is name of my database
$server = "localhost";
$db_handle = mysql_connect($server , $user_name, $password,"addresbook"); //adressbook is where all the tabels are
$db_found = mysql_select_db($database, $db_handle);
if (!$db_found) {
print "Database Found ";
$x=$_GET['fname'];
$y=$_GET['sname'];
$z=$_GET['address'];
$sql="INSERT INTO addresbook(First_Name,Surname,Address) VALUES('".$x."','".$y."','".$z."')";
mysql_query($sql,$db_handle);
}
else {
print "Database NOT Found ";
}
?>
</html>
here is mt html code:-
<form action="practic.php"method="get">
Firstname:<input type="text" name="fname"><br>
Lastname:<input type="text" name="sname"><br>
Address:<input type="text" name="address"><br>
<input type="submit">
</form>
btw i am using wamp server.Thanks in advance.
$db_found will be true on success, so your condition should be
if ($db_found) { // make DB changes etc.
and switch to MySQLi or PDO and use prepared statements as already mentioned, refer to the manual:
http://php.net/manual/en/mysqli.prepare.php
use mysqli_connect because mysql_connect is now deprecated.
$db_handle = mysqli_connect($server , $user_name, $password,$database);
refer here for connection
http://www.w3schools.com/php/func_mysqli_connect.asp
Hi change your code to use MysqLi or use PDO
<?php
$user_name = "root";
$password = "";
$database = "mysql"; //mysql is name of my database
$server = "localhost";
$con = mysqli_connect($server,$user_name,$password,'adresbook');//adresbook is where all the tabels are
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
// Change database to "adresbook"
$db_found = mysqli_select_db($con,'adresbook');
if ($db_found) {
print "Database Found ";
$x=$_GET['fname'];
$y=$_GET['sname'];
$z=$_GET['address'];
$sql="INSERT INTO addresbook(First_Name,Surname,Address) VALUES('".$x."','".$y."','".$z."')";
mysqli_query($con, $sql);
}
else {
print "Database NOT Found ";
}
?>
Your phpMyadmin should look like this with the database addresbook with a single s.

How do i reorganize my php code to include separate db info file

Can any of you guys help me to reorganize this code? I'll try to explain the problem below.
I have a db_connection.php wich includes the following (just my db info and don't worry, i am just using it locally):
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=webappeind;charset=utf8','root','');
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
But the problem is i have the following file that also includes my db info, but i do not know how to reorganize my code to get it working with my separate php file.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webappeind";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM zoekopdrachten ORDER BY titel DESC LIMIT 3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output gegevens van elke rij
while($row = $result->fetch_assoc()) {
echo "<div class='recenttoegevoegd'>"."<a href='#'>".$row["titel"]."</a>"."</div>";
}
} else {
echo "0 resultaten";
}
?>
You can put the connection information in a separate file called, say, conn.php where you mention the code related to database opening, including credentials. Then, in the calling file, say putdata.php, you use the "require" or "require_once" command to include that conn.php. Let the conn.php file return a connection. Somewhat like this :
<?php
function GetMyConn() {
$server_name = "localhost";
$db_name = "db_name_goes_here";
$db_user = "user_name_goes_here";
$db_pass = "password_goes_here_muahhhaa";
$db_full_addr = "mysql:host=" . $server_name . ";" . "dbname=" . $db_name;
$MyConn = new PDO($db_full_addr, $db_user, $db_pass);
$MyConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $MyConn;
}
?>
In the calling file, you would say, something like :
require_once "GetConn.php";
$MyConnHere = GetMyConn();
$SqlHere = "Sql Statemetn goes here...."
$SqlHere2 = $MyConnHere->prepare($SqlHere);
$SqlHere2->execute();
Also, I suggest you can download the source code of some open source PHP application, such as mantissa, and see how they have organized their code files, folders and settings.

Categories