can't connect to database with php (mysql) [duplicate] - php

If I want to put the connection in an external file, what part of this code should be in that external file?
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;

This part will go in external file e.g connection.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
and then your code will look like
require("connection.php");
try {
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
Till this part can go to external file, and can be used to open a connection where ever required.

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

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

PDO. How to put the connection in an external file

If I want to put the connection in an external file, what part of this code should be in that external file?
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
This part will go in external file e.g connection.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
and then your code will look like
require("connection.php");
try {
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
Till this part can go to external file, and can be used to open a connection where ever required.

PHP PDO connection failure [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 3 years ago.
Hey, so I am new with PDO, and I cannot figure out why my data will not insert into my tables. Much appreciated!
<?php
include("class.php");
$dbhost = "localhost";
$dbname = "db";
$dbuser = "user";
$dbpass = "pass";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$username = $_POST['username'];
$password = $_POST['password'];
$email = strtolower($_POST['email']);
$firstName = ucwords(strtolower($_POST['firstName']));
$lastName = ucwords(strtolower($_POST['lastName']));
$date = date("Y-m-d");
$hash = Secure::Encrypt($username, $password);
$sql = "INSERT INTO users (username,password,email,firstName,lastName,createDate) VALUES (:username,:password,:email,:firstName,:lastName,:date)";
$q = $conn->prepare($sql);
$q->execute(array(
':username'=>$username,
':password'=>$hash,
':email'=>$email,
':firstName'=>$firstName,
':lastName'=>$lastName,
':date'=>$date));
?>
If all of your table's field names match, I have found that PDO will sometimes fail if one of your array variables are empty.
to find out if any errors are being thrown, add the following after your new PDO declaration (PDO error reporting is silent by default):
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Then add try/catch around each PDO activity as follows:
try {
..Code Here...
}catch (PDOException $err) {
echo $err->getMessage();
}
Final Code:
<?php
include("class.php");
$dbhost = "localhost";
$dbname = "db";
$dbuser = "user";
$dbpass = "pass";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_POST['username'];
$password = $_POST['password'];
$email = strtolower($_POST['email']);
$firstName = ucwords(strtolower($_POST['firstName']));
$lastName = ucwords(strtolower($_POST['lastName']));
$date = date("Y-m-d");
$hash = Secure::Encrypt($username, $password);
$sql = "INSERT INTO users (username,password,email,firstName,lastName,createDate) VALUES (:username,:password,:email,:firstName,:lastName,:date)";
try {
$q = $conn->prepare($sql);
}catch (PDOException $err) {
echo 'Prepare Failed: '.$err->getMessage();
}
try {
$q->execute(array(
':username'=>$username,
':password'=>$hash,
':email'=>$email,
':firstName'=>$firstName,
':lastName'=>$lastName,
':date'=>$date));
}catch (PDOException $err) {
echo 'Execute Failed: '.$err->getMessage();
}
?>
Then please update with any errors you receive :)

Categories