Unable to connect to database? - php

This PHP is not working for me, it will not connect
Here is my code
<?php
$server = "localhost";
$database = "induadmi_db";
$username = "induadmi_main";
$password = "password";
$mysqlConnection = mysql_connect($server, $username, $password);
if (!$mysqlConnection)
{
echo "Please try later.";
}
else
{
mysql_select_db($database, $mysqlConnection);
}
?>

try this style:sample one and refer this following link
http://php.net/manual/en/function.mysql-connect.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

Works fine on my end with my own connection parameters..
You need to change this block to see the exact error...
if (!$mysqlConnection)
{
die(mysql_error());
}
This (mysql_*) 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. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
So nuff said..
Switch to PDO..
<?php
$dsn = 'mysql:dbname=induadmi_db;host=localhost';
$database = "induadmi_db";
$username = "induadmi_main";
$password = "password";
try
{
$dbh = new PDO($dsn, $username, $password ,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}

Related

Setting a mysql table in a variable

Okay so I'm using this code to store tables in a variable:
<?php
$host = "localhost";
$user = "x";
$password = "x";
try {
$account = new PDO("mysql:host=$host;dbname=account", $user, $password);
} catch(PDOException $e) {
die('connection cant be made');
}
try {
$player = new PDO("mysql:host=$host;dbname=player", $user, $password);
} catch(PDOException $e) {
die('connection cant be made');
}
and everything I do I get "connection can't be made". So I found another code and I switched to it and everything works.
<?php
$host = "localhost"; // Ip-ul de la server
$user= "xx"; // User-ul de conectare la database
$password = "xx"; // Parola de conectare la database
mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db('account');
mysql_set_charset('utf8');
?>
but now I have no db assigned to $account and $player and I can't use my site properly. Ideas?
In $e you have reason why you can't connect to database. Catch exception and do nothing with it...
<?php
define('__DEBUG', true);
try {
$account = new PDO("mysql:host=$host;dbname=account", $user, $password);
} catch(PDOException $e) {
if(__DEBUG) {
print $e->getMessage();
}
die('connection cant be made');
}
for use 2 connections in (not so^) old way style:
$con1 = mysqli_connect();
$con2 = mysqli_connect();
mysqli_query('query', $con1);
mysqli_query('query', $con2);
^ use mysqli_ instead mysql_

Failing testing database connection in php

I've set up a database using MAMP.
When I try the following test, I only receive a blank page. Fairly new to this, and I've tried different suggestions found on the web with no luck.
Tried using both port and socket.
<?php
$user = 'root';
$password = 'root';
$db = 'test';
$host = 'localhost';
$port = 3306;
$socket = "/Applications/MAMP/tmp/mysql/mysql.sock";
$link = mysql_connect(
"$host:$socket",
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
if (!$link){
echo "ERROR";
}
else {
echo "Success";
}
mysql_close($link);
?>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;test", $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();
}
?>
Would you like to try PDO ?!
<?php
$dsn = "mysql:host=localhost;dbname=databasenamehere";
$user = 'root';
$pass = '';
$option = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$connect = new PDO($dsn, $user, $pass,$option);
$connect->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $r) {
echo 'Failed' . $r->getMessage();
}

How to connect MySQL db using new XAMPP

Old connection method mysql_connect maybe deprecated from PHP7 so what is the best way to connect and query in mysql using XAMPP or how I implement PDO in my bellow script.
<?php
$key = $_GET['key'];
$array = array();
$con = mysql_connect("localhost", "root", "");
$db = mysql_select_db("search", $con);
$query = mysql_query("select * from ajax_example where name LIKE '%{$key}%'");
while ($row = mysql_fetch_assoc($query)) {
$array[] = $row['name'];
}
echo json_encode($array);
?>
Database connection using mysqli_* :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
For further mysqli_* statement syntax refer: Mysqli_* Manual
Database connection using PDO_* :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $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();
}
?>
For further PDO_* statement syntax refer PDO_* Manual
$conn = new Connection();
$query = "select * from ajax_example where name LIKE '%{$key}%'";
$res = $conn->execute_query($query)->fetchall(PDO::FETCH_ASSOC);
if (!empty($res))
{
$result['data'] = $res;
echo json_encode($result);
}

Need help connecting my database to PHP

I am trying to connect my database to my PHP code using this code:
<html>
<head>
<title>Landing page</title>
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
<?php
// Check if username and password are correct
if ($_POST["username"] == "logintest" && $_POST["password"] == "access123!") {
// If correct, we set the session to YES
session_start();
$_SESSION["logged_in"] = "YES";
echo "<h1>You are now logged in</h1>";
echo "<p><a href='secure1.php'>Link to protected file</a></p>";
echo "<p><a href='secure2.php'>Link to protected file #2</a></p>";
}
else {
// If not correct, we set the session to NO
session_start();
$_SESSION["logged_in"] = "NO";
echo "<h1>You are NOT logged in </h1>";
echo "<p><a href='secure1.php'>Link to protected file</a></p>";
echo "<p><a href='secure2.php'>Link to protected file #2</a></p>";
}
?>
<p>Public Page</p>
<p>Logout</p>
</body>
</html>
Instead of using the inline username and password, I would like to use the databases username and password from a specific table. I just cant get it to work for some reason, and I am finding it really hard. It would be great if anyone could help.
Note:
You have to establish first a connection to your database. Replace the necessary data inside the connection
I used mysqli_* prepared statement rather than deprecated mysql_*
Replace your if ($_POST["username"] == "logintest" && $_POST["password"] == "access123!") { with if($checklog > 0 ){
Code:
/* ESTABLISH FIRST YOUR CONNECTION TO YOUR DATABASE */
$con = new mysqli("host", "User", "Password", "Database"); /* REPLACE NECESSARY DATA */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if($stmt = $con->prepare("SELECT Username, Password FROM user_login WHERE Username = ? AND Password = ?")){
$stmt->bind_param("ss",$_POST["username"],$_POST["password"]);
$stmt->execute();
$stmt->store_result();
$checklog = $stmt->num_rows;
if($checklog > 0){
/* HERE IS YOUR CODE WITH SUCCESSFUL LOGIN */
}
else {
/* HERE IS YOUR CODE WITH UNSUCCESSFUL LOGIN */
}
$stmt->close();
}
There are several ways to connect to MySQL. However, just knowing how to connect isn't enough. You need to learn how to use it as well. Therefor I'm first giving you a couple of links to MySQLi and PDO:
PHP: MySQLi - Manual
PHP: PDO - Manual
Now to answer your question, here are some commonly used methods to connect to mysql:
MySQLi Object Oriƫntated Style
<?php
$dbhost = ""; //Server Address
$dbname = ""; //Database Name
$dbuser = ""; //Database User
$dbpass = ""; //Database Password
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno){
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
?>
MySQLi Procedural Style
<?php
$dbhost = ""; //Server Address
$dbname = ""; //Database Name
$dbuser = ""; //Database User
$dbpass = ""; //Database Password
$mysqli = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_error()){
echo "Failed to connect to MySQL: (" . mysqli_connect_error() . ")";
}
?>
PDO Object Oriƫntated Style
<?php
$dbhost = ""; //Server Address
$dbname = ""; //Database Name
$dbuser = ""; //Database User
$dbpass = ""; //Database Password
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try{
$pdo = new PDO($dsn, $dbuser, $dbpass, $options);
}
catch(PDOException $e){
echo $e->getMessage();
}
?>

mysql_select_db returns false while mysql_error returns nothing

I'm trying to connect to a database, but mysql_select_db always returns false. If I just use the first parameter of mysql_select I get the error: Access denied for user ''#'localhost' to database 'newboston', if I enter the connection link as the second parameter mysql_error returns nothing. Anyone knows what's going on?
<?php
$dbServer = 'localhost';
$dbUserName = 'root';
$dbPassword = 'password';
$database = 'newboston';
$db = mysqli_connect($dbServer, $dbUserName, $dbPassword);
$connectFailed = 'Could not connect to ' . $dbServer . '.';
if($db)
{
if(mysql_select_db($database, $db))
{
echo 'Connected to ' . $database;
}
else
{
echo 'Could not connect to ' . $database;
die(mysql_error());
}
}
else
{
echo $connectFailed;
}
?>
You're mixing mysql and mysqli:
$db = mysqli_connect($dbServer, $dbUserName, $dbPassword);
should be:
$db = mysql_connect($dbServer, $dbUserName, $dbPassword);
(actually you should be using mysqli as mysql is deprecated).
You're mixing mysqli_* functions with mysql_* functions.
May I suggest learning PDO MySQL instead?

Categories