Need help connecting my database to PHP - 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();
}
?>

Related

Cant perform an SQL update when using php varibles

I just noticed that i can not perform SQL updates when i am using PHP varibles from the link
My code (I don't noticed any errors, and no error output)
<?php
if ($_POST && isset($_POST['hdduid'], $_POST['status'])) {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'L24wmc1nJBVP90q9yY';
$dbname = 'watt';
try {
// Try to connect
$dbh = new PDO(
'mysql:host='.$dbhost.';dbname='.$dbname,
$dbuser,
$dbpass
);
// Data
$hdduid = $_POST['hdduid'];
$status = $_POST['status'];
// query
$sql = "UPDATE users SET paid=':status' WHERE hdduid=':hdduid'";
$q = $dbh->prepare($sql);
$q->execute(array(
':message' => $message,
':email' => $email
));
// Null connection
$dbh = null;
} catch (PDOException $e) { // if exception
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
I edited the code, it still wont working
You need to use
mysqli_real_escape_string
Not
mysql_real_escape_string
You can not mix mysql with MySQLi
Here is another solution using prepared statements.
$servername = "localhost";
$username = "root";
$password = "L24wmc1nJBVP90q9yY";
$dbname = "ft";
// Create connection
$connection = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$paid = $_GET["status"];
$hdduid = $_GET["hdduid"];
//Prepared statements
$statement = $connection->prepare("UPDATE users SET paid = ? WHERE hdduid = ?");
$statement->bind_param("ss", $paid, $hdduid);
if(!$statement->execute()) {
echo "Error updating record: " . $statement->error;
} else {
echo "Record updated successfully";
}
$statement->close();
$connection->close();
Here is a solution. It uses mysqli_real_escape_string instead of mysql_real_escape_string. I also changed the name of $status to $paid for better readability. Good luck!
$servername = "localhost";
$username = "root";
$password = ""; //$password = "L24wmc1nJBVP90q9yY";
$dbname = "test"; //$dbname = "ft";
// Create connection
$connection = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$hdduid = $_GET["hdduid"];
$paid = $_GET["status"];
$sql = "UPDATE users SET paid='$paid' WHERE hdduid='$hdduid'";
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $connection->error;
}
$connection->close();

PHP MySQL function dies

Ive written my function just to check if the database connection is working.
And it seems like he cant connect to my database, thats no problem, but he dies at the point where i run the function.
function testconnection() {
global $dbhost, $dbuser, $dbpassword, $dbname;
error_reporting(E_ERROR);
$conn = mysql_connect($dbhost, $dbuser, $dbpassword);
$dbconn = mysql_select_db($dbname);
if ( !$conn ) {
return "connfailed";
}
if ( !$dbcon ) {
return "dbconnfailed";
}
}
It stops any further building of the website.
All variables are defined. This function is just used to display an error message if it returns "dbconnfailed".
but even with echo testconnection(); it displays nothing.
can be seen here
but I host this at a big company and on localhost via xampp
it isnt working on one.com but it is working on xampp
You did not add your connection to $dbconn
$dbconn = mysql_select_db($dbname,$dbconn);
Pls Don't use the deprecated and insecure mysql_*-functions. They have been deprecated since PHP 5.5 (in 2013) and were completely removed in PHP 7. Use MySQLi or PDO instead
If you are using mysqli: Try this one..
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM usertable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
use mysqli library
function testconnection() {
global $dbhost, $dbuser, $dbpassword, $dbname;
error_reporting(E_ERROR);
$conn = mysqli_connect($dbhost, $dbuser, $dbpassword);
/* check connection */
if (mysqli_connect_errno()) {
return "connfailed " . mysqli_connect_error();
}
$dbconn = mysql_select_db($dbname);
if(!$dbcon) {
return "dbconnfailed " . mysqli_error($dbconn);
}
}

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);
}

php mysql connection get error message

this is my first php code , i am trying to connect to a database with user name = "root" and password = "root"
i have a connection file called dbConnection.php
as following :
<?php
echo "in connection file";
$hostname = "localhost";
$username = "root";
$password = "root";
$db = "ledDB";
echo "<br> db-connection : vars definde ";
//connection to the database
$conn = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
echo "db-connection : initilize connection ";
mysql_select_db($db);
echo "db-connection : connection done";
// Check connection
echo "Connected successfully";
?>
and i call it in a file called what.php :
<?php
echo "Hello";
include "dbConnection.php";
echo "ohhhh";
?>
this returns status code 500 which is internal server error
but i want to know what is the error to fix it how can i get the error message ?
i tried
$conn = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
but it is not returning any thing.
can any one help me please ?
if you are having password on localhost then use password otherwise leave it blank
$con = mysqli_connect("localhost","root","yourpassword","yourdb");
You mysqli_connect() method.
<?php
echo "in connection file";
$hostname = "localhost";
$username = "root";
$password = "root";
$db = "ledDB";
echo "<br> db-connection : vars definde ";
//connection to the database
$conn = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
echo "db-connection : initilize connection ";
mysqli_select_db($conn,$db);
echo "db-connection : connection done";
// Check connection
echo "Connected successfully";
?>
First Thing is to Change your connection method to mysqli or my personal favorite PDO.
PDO Example:
class db extends pdo{
//Website Variables
public $sitedb = '';
public $siteconfig;
public $sitesettings = array(
'host' => 'localhost',
'database' => 'yourdb',
'username' => 'youruser',
'password' => 'yourpass',
);
public function __construct(){
$this->sitedb = new PDO(
"mysql:host={$this->sitesettings['host']};" .
"dbname={$this->sitesettings['database']};" .
"charset=utf8",
"{$this->sitesettings['username']}",
"{$this->sitesettings['password']}"
);
$this->sitedb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
}
$db = new db();
Then you can extend your PDO class to new classes after including the db.php page.
Example Select:
class yourclass extends db {
public function SelectUsers() {
global $db;
$query = <<<SQL
SELECT email
FROM users
WHERE active = :active
SQL;
$resource = $db->sitedb->prepare( $query );
$resource->execute( array (
':active' => 1,
));
$count = $resource->rowCount();
foreach($resource as $user){
$this->email = $user['email'];
}
}
}
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydb";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
// make the current db
$db_selected = mysqli_select_db ( $conn , $dbname );
if (!$db_selected) {
die ('Can\'t connect to Database : ' . mysql_error());
}
?>

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