How to connect MySQL db using new XAMPP - php

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

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

I am trying to retrieve data from my database using PDO Fetch object

I am trying to retrieve data from my database using PDO Fetch object and it says
Fatal error: Uncaught Error: Call to undefined method mysqli_result::execute()
what I'm doing wrong
This is what I have tried
<?php
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "messages_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$getquery = $conn->query('select col_name from db where id = 2');
$getquery->execute();
$result = $getquery->fetch(PDO::FETCH_OBJ);
?>
<div><?= $result->col_name; ?></div>
Firstly, don't mix PDO and mysqli. Stick to one. Here's a PDO example. You first need to create a new PDO object. and connect to DB at the start
$servername = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "dbname";
try{
$pdo = new PDO("mysql:host=$servername;dbname=$dbname",$dbusername,
$dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
print "Error! Unable to connect: " . $e->getMessage() . "<br/>";
die();
}
$rtrv = "select col_name from db where id = 2"
$stmt = $pdo->prepare($rtrv);
//Execute.
$stmt->execute();
//Fetch.
$user = $stmt->fetch(PDO::FETCH_ASSOC);
// Do whatever you want after this

PHP and mysql connection not working

I have written following code to connect mysql in php but I am not getting output.
<?php
$servername = "localhost";
$username = "root";
$password = "pravin";
$mysql_conn = new mysqli($servername, $username, $password);
if ($mysql_conn->connect_error) {
die("Connection failed: ". $mysql_conn->connect_error);
}
echo "Connected successfully";
$name = $_POST["microorganism"];
echo $name;
$db_selected = mysql_select_db('yieldofvanillin', $mysql_conn);
if (!$db_selected){
die ('Can\'t use : ' . mysql_error());
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
$result = $mysql_query($query);
while ($line = myql_fetch_array($result, MYSQL_ASSOC)) {
echo $line["Substrate"];
echo $line["products"];
echo $line["Microorganism"];
echo $line["yield"];
echo $line["Reference"];
}
mysql_close($mysql_conn);
?>
The database name is "yieldofvanillin" and it has five column. I an getting output Connected successfully. After that no output. Please let me know the bug in code.
i have remove errors. which i mention in comments. Code Reference PHP Manual. you should read this manual (strongly recommended)
<?php
$mysqli = new mysqli("localhost", "root", "pravin", "yieldofvanillin");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["Substrate"];
echo $row["products"];
echo $row["Microorganism"];
echo $row["yield"];
echo $row["Reference"];
}
/* free result set */
$result->free();
}
you're mixing mysqli and mysql libraries.
the code should be:
<?php
$servername = "localhost";
$username = "root";
$password = "pravin";
$mysql_conn = new mysqli($servername, $username, $password);
if (mysqli_connect_errno()) {
die("Connection failed: ". mysqli_connect_error());
}
echo "Connected successfully";
$name = $_POST["microorganism"];
echo $name;
$db_selected = mysqli_select_db($mysql_conn,'yieldofvanillin');
if (!$db_selected){
die ('Can\'t use : ' . mysqli_error($mysql_conn));
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
$result = mysqli_query( $mysql_conn,$query);
while ($line = mysqli_fetch_assoc($result)) {
echo $line["Substrate"];
echo $line["products"];
echo $line["Microorganism"];
echo $line["yield"];
echo $line["Reference"];
}
mysqli_close($mysql_conn);
?>
Remove error in your code.Read carefully php manual.
<?php
$servername = "localhost";
$username = "root";
$password = "pravin";
$db = "yieldofvanillin";
// Create connection
$mysqli = new mysqli($servername, $username, $password, $db);
/* connection string*/
if ($mysqli->connect_errno) {
die("Connection failed: " . $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row["Substrate"];
}
$result->free();
}
$mysqli->close();
?>
Your output not showing because mysql_fetch_array is not correct.Because you are mixing mysql_ and mysqli_ functions and you called myql_fetch_array that doesn't exist in mysqli. MySQL and MySQLi are two different PHP extensions and they cannot be mixed. Because the former is deprecated in mysqli

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

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

Categories