How to change mysql_connect into PDO. Updating form - php

I'm new to programming and just changed from mysql to mysqli, but when i found my login script on the net it was written with PDO. So now i'm onto that ;D
How can i change this php file to use PDO to update my database?!
Config.php
<?php
// These variables define the connection information for your MySQL database
$username = "usr";
$password = "pass";
$host = "host";
$dbname = "databasee";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try { $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); }
catch(PDOException $ex){ die("Failed to connect to the database: " . $ex- >getMessage());}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
PHP:
<?php
if($_POST) {
$connect = mysqli_connect('host', 'username', 'password', 'dbname');
require("config.php");
if(empty($_SESSION['user'])) {
header("Location: index.php");
die("Redirecting to ../index.php");
} else {
// get data from model form meny.php
$valt_objekt_id = mysqli_escape_string($connect, strip_tags($_POST['valt_objekt_id']));
$valt_objekt_nummer = mysqli_escape_string($connect, strip_tags($_POST['valt_objekt_nummer']));
$valt_objekt_alias = mysqli_escape_string($connect, strip_tags($_POST['valt_objekt_alias']));
$valt_objekt_leverans = mysqli_escape_string($connect, strip_tags($_POST['valt_objekt_leverans']));
$valt_objekt_adress = mysqli_escape_string($connect, strip_tags($_POST['valt_objekt_adress']));
// update database
$sql = "UPDATE `objekt`
SET `objekt_nummer` = '$valt_objekt_nummer',
`objekt_alias`= '$valt_objekt_alias',
`objekt_leverans` = '$valt_objekt_leverans',
`objekt_adress` = '$valt_objekt_adress'
WHERE `objekt_id` = '$valt_objekt_id'";
//this is required for almost every mysqli_* function
$result = mysqli_query($connect, $sql); //the example
//mysqli can update multiple rows at a time
// if successfully updated.
if($result){
echo "Uppdateringen lyckades <br> <a href='../objekt.php'>Gå tillbaka</a>";
} else {
echo mysql_error();
}
}
}
?>

Here is the PDO version of your script:
if($_POST) {
if(empty($_SESSION['user'])) {
header("Location: index.php");
die("Redirecting to ../index.php");
} else {
require("config.php");
// get data from model form meny.php
$valt_objekt_id = $_POST['valt_objekt_id'];
$valt_objekt_nummer = $_POST['valt_objekt_nummer'];
$valt_objekt_alias = $_POST['valt_objekt_alias'];
$valt_objekt_leverans = $_POST['valt_objekt_leverans'];
$valt_objekt_adress = $_POST['valt_objekt_adress'];
// update database
$sql = "UPDATE `objekt`
SET `objekt_nummer` = :objekt_nummer,
`objekt_alias`= :objekt_alias,
`objekt_leverans` = :objekt_leverans,
`objekt_adress` = :objekt_adress
WHERE `objekt_id` = :objekt_id";
$stmt = $db->prepare($sql);
$result = stmt->execute(array(':objekt_nummer' => $valt_objekt_nummer,
':objekt_alias' => $valt_objekt_alias,
':objekt_leverans' => $valt_objekt_leverans,
':objekt_adress' = $valt_objekt_adress,
':objekt_id' => $valt_objekt_id
));
if($result){
echo "Uppdateringen lyckades <br> <a href='../objekt.php'>Gå tillbaka</a>";
} else {
print_r($db->errorInfo());
}
}
}
Learn more about PDO prepared statments

Related

SQL Login System

I coded this login system, but whenever I try to log in with the only username and password included in my database table, I get redirected to index.php?error=sqlerror. I checked the code for spelling mistakes but there are none. Could this be a problem with the database connection? I use MAMP. I have checked the database and it displays the Success message so it seems to be working. Do you know what I am doing wrong? Thank you!
DATABASE CONNECTION (file name: dbh.inc.php)
$servername = "127.0.0.1";
$dBUsername = "root";
$dBPassword = "";
$dBName = "gallerydatabase";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
echo "Error: Unable to connect to MySQL.";
}
echo "Success";
mysqli_close($conn);
?>
LOG-IN PHP CODE (file name: login.inc.php)
if (isset($_POST['login-submit'])) {
require 'dbh.inc.php';
$mailuid = $_POST['mailuid'];
$password = $_POST['pwd'];
if (empty($mailuid) || empty($password)) {
header ("Location: ../index.php?error=emptyfields");
exit();
}
else {
$sql = "SELECT * FROM users WHERE uidUsers=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header ("Location: ../index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($password, $row['pwdUsers']);
if ($pwdCheck == false) {
header ("Location: ../index.php?error=wrongpwd");
exit();
}
else if ($pwdCheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
header ("Location: ../index.php?login=sucess");
exit();
}
else {
header ("Location: ../index.php?error=wrongpwd");
exit();
}
}
else {
header ("Location: ../index.php?error=nouser");
exit();
}
}
}
}
else {
header ("Location: ../index.php");
exit();
}
I think the problem is in your file dbh.inc.php, you create the connection $conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName); and later you close it as well mysqli_close($conn);.
So by the time you come to use $conn in login.inc.php your connection is closed. What you need to do is write a function in dbh.inc.php that returns a live connection (don't call close), use that to do your DB queries / insert and after that close the connection.
A reusable database class can be written (functional style) as follows
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
trait DBInfo {
protected $servername = "127.0.0.1";
protected $username = "root";
protected $password = "";
protected $dbname = "gallerydatabase";
}
class Database{
use DBInfo;
function __construct() {}
function connection(){
$conn = new mysqli($this->servername, $this->username,
$this->password, $this->dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
$conn->autocommit(FALSE);
return $conn;
}
}
function select($sql, $fn2bind_takestmt, $fn2process_row_return_result){
try{
$result = array();
$conn = $this->connection();
$stmt = $conn->prepare($sql);
$fn2bind_takestmt($stmt);
$stmt->execute();
$rowset = $stmt->get_result();
while ($row = $rowset->fetch_assoc()) {
$obj = $fn2process_row_return_result($row);
array_push($result, $obj);
}
}catch(Exception $e) {
$result = NULL;
throw $e;
}finally{
if(isset($rowset))$rowset->close();
if(isset($stmt))$stmt->close();
if(isset($conn))$conn->close();
}
return $result;
}
// You can introduce functions for insert, update and delete as well
}
?>
and then for database selects for example login check
<?php
function allow_login($user, $pwd){
$sql = "SELECT count(*) rec_count FROM users WHERE uidUsers=? and pwdUsers=?"
$db = new Database();
$result = $db->select($sql,
function($stmt) use($user, $pwd){
$stmt->bind_param("ss", $user, $pwd);
},
function($row){
if($row['rec_count'] > 0){// or whatever
return TRUE;
}
return FALSE;
}
);
if(isset($result)){
return $result[0];
}
return $result;
}
?>

External file with PDO connection not working

I realize this question has been asked in some form or another multiple times, but none of the solutions on the other versions of this question work for me.
These two files have no issues:
/blog/login.php
<?php
include('core/init.php');
if (empty($_POST) === false){
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) || empty($password)) {
$errors[] = 'Missing username and/or password.';
} else if (user_exists($username) === false) {
$errors[] = 'User doesn\'t exist.';
}else if (user_active($username) === false) {
$errors[] = 'User account not activated.';
}else {
//
}
print_r($errors);
}
?>
/blog/core/init.php
<?php
require('database/connect.php');
require('functions/users.php');
require('functions/general.php');
session_start();
$errors = array();
?>
I'm just including them to show you how connect.php is require()'d (indirectly) in users.php.
/blog/core/database/connect.php
<?php
$dbname = "xxx_forms";
$servername = "mysql.xxx.com";
$usr= "xxx_xxx";
$pass = "xxxxxxxx";
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $usr, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
This connection itself doesn't trigger any errors...
/blog/core/functions/users.php
<?php
function user_exists($username) {
$ret = '';
try {
$sql = "SELECT COUNT(id) FROM registration WHERE user = '$username';";
$q = $pdo->query($sql);
$f = $q->fetch();
$ret = $f[0];
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
return ($ret == 1) ? true : false;
}
However, when we get to users.php, I always get an error at the $q = $pdo->query($sql); line, apparently because PHP doesn't know what $pdo is. On the other hand, when I include the code from connect.php, so that it is not in an external file (exactly like below, but not commented out):
function user_exists($username) {
//$dbname = "xxx_forms";
//$servername = "mysql.xxx.com";
//$usr= "xxx_xxx";
//$pass = "xxxxxxxx";
$ret = '';
try {
//$pdo = new PDO("mysql:host=$host;dbname=$dbname", $usr, $pass);
$sql = "SELECT COUNT(id) FROM registration WHERE user = '$username';";
$q = $pdo->query($sql);
$f = $q->fetch();
$ret = $f[0];
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
return ($ret == 1) ? true : false;
}
...everything works the way it is supposed to.
How do I make it work when the PDO connection is done in the external file connect.php?
Further to my comment, you need to do something like this:
/config.php
<?php
define('DS',DIRECTORY_SEPARATOR);
define('DB_HOST','localhost');
define('DB_NAME','database');
define('DB_USER','root');
define('DB_PASS','');
define('ROOT_DIR',__DIR__);
define('FUNCTIONS',ROOT_DIR.DS.'functions');
# Add the connection function
require_once(FUNCTIONS.DS.'connect.php');
# Start session
session_start();
# Get the connection
$pdo = connect();
/functions/connect.php
function connect()
{
$pdo = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
/functions/user_exists.php
<?php
function user_exists($pdo,$username)
{
$ret = 0;
try {
$sql = "SELECT COUNT(id) as count FROM registration WHERE user = :username";
$q = $pdo->prepare($sql);
$q->execute(array(":username"=>$username));
$f = $q->fetch(PDO::FETCH_ASSOC);
$ret = $f['count'];
}
catch (PDOException $e) {
die("Could not connect to the database ".DB_NAME.":" . $e->getMessage());
}
return ($ret == 1);
}
Here is an example of use:
/index.php
<?php
# Add the basic stuff
require(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Add our functions
require(FUNCTIONS.DS.'user_exists.php');
require(FUNCTIONS.DS.'general.php');
# Example of use
print_r(user_exists($pdo,'username#email.com'));

How do I reconnect my web pages on my website after updating to PHP 7 with a MySQL database 5.0.0?<?

I added the i updates to communicate with the database & now the page links don't work.
<?php
// Connect to database
$link=mysqli_connect('localhost', 'xxxxx', 'xxxxx');
mysqli_select_db($link, 'waddellc_PHRDB');
$sql = "SELECT * FROM quotes ORDER BY id";
$result = mysqli_query($link, $sql) or die(mysql_error());
$tenant_quotes = array();
$owner_quotes = array();
while($row = mysqli_fetch_array($result)) {
This should do the work, using PDO :
$servername = "localhost";
$username = "username";
$password = "password123";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=databaseName", $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();
}
if(!is_null($conn)){
$stmt = $conn->prepare("SELECT * FROM quotes ORDER BY id");
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
}
I also think you need to update your database, it's quite old now.

Using PHP in HTML to send object values to mysql database

I am creating a website where it sends values from a JavaScript object into a MySQL database via PHP
Here is the code:
<!DOCTYPE html>
<html>
<body>
<p>Creating a JavaScript Object.</p>
<p id="demo"></p>
<script>
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
</script>
</body>
</html>
Overall, my question is how to send the objects data to the MySQL using PHP?
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
If I type the code in before it prints out:
connect_error) {die("Connection failed: " . $conn->connect_error);} echo "Connected successfully";?>
It sounds to me like you are trying to jump from not knowing how to work with PHP and MySQL to also adding JavaScript.
First let me give you an example of how to work with all of those things.
Here is the repo with all of these files: https://github.com/Goddard/simplelogin-example.
This is what connects you to the database:
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
define("__DB_NAME__", 'job');
define("__DB_DSN__", 'mysql:dbname=' . __DB_NAME__ . ';host=127.0.0.1');
define("__DB_USERNAME__", 'root');
define("__DB_PASSWORD__", '');
if(session_id() == '') {
session_start();
}
if(!isset($_SESSION['username']))
{
$_SESSION['username'] = NULL;
}
//database setup
try {
$db = new PDO ( __DB_DSN__, __DB_USERNAME__, __DB_PASSWORD__ );
$db->query ( "use " . __DB_NAME__);
}
catch ( PDOException $e ) {
echo 'Could not connect : ' . $e->getMessage ();
}
?>
This is what works with the database information:
<?php
include("db.php");
if(trim(htmlentities(addslashes(filter_input(INPUT_GET, 'type')), ENT_QUOTES)) === "loginUser")
{
try {
$username = trim(filter_input(INPUT_GET, 'username'));
$password = trim(filter_input(INPUT_GET, 'password'));
$fetch = $db->prepare("SELECT * FROM `users` WHERE user_name = :username");
$fetch->bindParam(':username', $username, PDO::PARAM_STR);
$fetch->execute();
$result = $fetch->fetch(PDO::FETCH_OBJ);
if($result)
{
if(password_verify($password, $result->password_hash))
{
$currentDateTime = date('Y-m-d H:i:s');
$update = $db->prepare("UPDATE `users` SET `last_login` = :lastlogin WHERE `client_id` = :clientid");
$update->bindParam(':lastlogin', $currentDateTime);
$update->bindParam(':clientid', $result->client_id);
$loginUpdate = $update->execute();
$resultArray['error'] = 0;
$resultArray['errorMessage'] = "None";
$resultArray['userName'] = $result->user_name;
$_SESSION['username'] = $result->user_name;
echo json_encode($resultArray);
}
else
{
$resultArray['error'] = 1;
$resultArray['errorMessage'] = "Incorrect Password";
echo json_encode($resultArray);
}
}
else
{
$resultArray['error'] = 1;
$resultArray['errorMessage'] = "Incorrect Username";
echo json_encode($resultArray);
}
} catch (PDOException $e) {
$resultArray['error'] = 1;
$resultArray['errorMessage'] = $e->getMessage();
echo json_encode($resultArray);
}
}

PHP: PDO prepare() causing halt in script

I am working on a simple database helper for part of a test site. I want to be able to access a database by simply doing:
require_once 'include/database_system.php'
...
$row = DB_query("SELECT userID FROM users WHERE username = :username",
array(':username' => $ourUsername));
So I've written up a little script to do so:
<?php
session_start();
$username = "xxxx";
$password = "xxxx";
$host = "localhost";
$dbname = "xxxx";
$dboptions = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
var_dump($db);
}
catch(PDOException $ex)
{
die("MySQL: Failed to connect to API Testing Database");
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
var_dump($db);
// break magic quotes
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function break_magic_quotes(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
break_magic_quotes($value);
}
else
{
$value = stripslashes($value);
}
}
}
break_magic_quotes($_POST);
break_magic_quotes($_GET);
break_magic_quotes($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
function DB_query($query, $queryArgs)
{
global $db;
echo 'TRYING TO QUERY SERVER ';
var_dump($query);
var_dump($queryArgs);
var_dump($db);
try
{
echo 'PREPARE ';
$stmt = $db->prepare($query);
echo 'EXECUTE ';
$result = $stmt->execute($queryArgs);
}
catch(PDOException $ex)
{
echo "QUERY FAILED: $query";
die("Query failed: " . $query);
return;
}
echo 'SERVER QUERY OK';
return $stmt->fetch();
}
So naturally, I'm working on a bit of form action code for the login page, by doing:
require_once 'database.php'
....
$row = DB_query("SELECT * FROM users WHERE username = :username",
array(':username' => $_POST['u']) );
The output is not very conclusive at all. Not only does it fail to get past the $db->prepare() statement, but it doesn't even look like the PDO is valid.
object(PDO)#1 (0) { } object(PDO)#1 (0) { } TRYING TO LOGINobject(PDO)#1 (0) { } TRYING TO QUERY SERVER string(46) "SELECT * FROM users WHERE username = :username" array(1) { [":username"]=> string(4) "derp" } NULL PREPARE
I don't know why it would be doing any of this. I have checked the PHP settings and it looks like PDO is properly turned on. I have checked everything up and down and I haven't been able to get anywhere. If anyone has any insight, that would be great.

Categories