How to CRUD using PDO Connection? - php

I want to CRUD using PDO Connection
I know how to create insert update and delete using msql_query() but I have no idea how to do that with PDO Connection.

Below is the example of that
class connection{
public $cnn;
public function __construct(){
$host = 'localhost';
$db_name = "db_name";
$username = "db_username";
$password = "db_password";
try {
$this->cnn = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function select($query){ //this function is created for get data
$result = $this->cnn->query($query);
return $result->fetchAll(PDO::FETCH_ASSOC);
}
public function insert($query){ //this function is created for insert data. it will be return last inserted id.
$this->cnn->exec($query);
return $this->cnn->lastInsertId();
}
public function update($query){ //this function is created for update data and it will be return effected rows (which are updated)
return $this->cnn->exec($query);
}
public function delete($query){ // this function is use to delete data.
return $this->cnn->exec($query);
}
}
$action = new connection;
$result = $action->select("select * from table_name");
print_r($result);
$result = $action->insert("insert into table_name set column_1 = 'first_value', column_2='second_value'");
$result = $action->update("update table_name set column_1 = 'first_value', column_2='second_value' where id=1");
$result = $action->delete("delete from table_name where id=1");

Maybe this is an easier way to do it. now the only thing you have to do is call the functions. Enjoy (:
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "database";
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function updateuser($pdo, $username, $password, $id){
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password, $id]);
}
function deleteuser($pdo, $id){
$sql = 'DELETE FROM users WHERE id = ?';
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
}
function createuser($pdo, $username, $password){
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password]);
}
function readuser($pdo, $id){
$sql = "SELECT id, username FROM users WHERE id=?";
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}

Related

Issue with PDO Connection

i am new to this so dont be rude :D
I have 3 file: database.php, init.php and user.php
Here the init.php:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
require 'database.php';
require 'functions/user.php';
$errors = array();
Here the database.php:
<?php
$db_host = "localhost";
$db_name = "xxxx";
$db_user = "xxxx";
$db_pw = "xxxx";
try {
$conn = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_pw);
} catch(PDOException $e) {
die("Verbindung fehlgeschlagen: " . $e->getMessage());
}
And here the user.php:
<?php
function userExists($user) {
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}
So the error message:
Notice: Undefined variable: conn in /mnt/web109/b2/35/57848035/htdocs/includes/functions/user.php on line 4 Fatal error: Call to a member function prepare() on null in /mnt/web109/b2/35/57848035/htdocs/includes/functions/user.php on line 4
The function userExists() is called in another file named login.php. In login.php i have already required init.php. The error message appears when i want to login.
So i hope you can help me.
Thx
$conn is not available in your function since it is in a different scope. Pass it as a parameter or declare it as a global variable.
function userExists($user, $conn){
// ...
}
or
function userExists($user){
global $conn;
// ...
}
In your userExists function you are calling $conn variable which isn't global scope (Give a small look here)..
You can use one of these:
function userExists($user, $conn){
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}
OR
function userExists($user){
global $conn; //<--- bad practi
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}
OR
use of $GLOBALS variable
function userExists($user){
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $GLOBALS['conn']->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}

retrieve values mysqli_fetch

I'm trying to get the id value from a table called usuario in the database, passing $username as parameter, the function $conexion->connect() returns a mysqli object. The functions give me no errors but it doesn't return the value from database. Am I missing something? or making any mistake.
Thanks for help.
public function checkUserNameExists($username){
$conexion = new Connection();
$conexion->connect();
$query = "select id from usuario where username = ?";
$reg = 0;
$stmt= $conexion->connect()->prepare($query);
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch()){
$reg = $id;
}
$stmt->close();
return $reg;
}
This is the function connect() what is located in a class file "Connection"
public function connect(){
$mysqli = new mysqli($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return $mysqli
}
public function checkUserNameExists($username){
$conexion = new Connection();
$conn = $conexion->connect();
$query = "select id from usuario where username = ?";
$reg = 0;
$stmt= $conn->prepare($query);
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch()){
$reg = $id;
}
$stmt->close();
return $reg;
}
You should store the return value of new mysqli in a variable, and then use that variable to make queries or prepares from.

Querying Mysql with PDO fetch returns false

I am trying to query my database in PDO and have the output on a form. However the fetch statement does not work. The code is
try {
include '../../config/database.php';
$database = new Database();
$db = $database->getConnection();
//prepare query
$query = "select
payment_id, payment_supplier, payment_ref, payment_cost_rating, payment_amount
from
payments
where
payment_id = ?
limit 0,1";
$stmt = $db->prepare( $query );
//this is the first question mark
$stmt->bindParam(1, $_REQUEST['myData']);
//execute our query
if($stmt->execute()){
var_dump($stmt->fetch());
//store retrieved row to a variable
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//values to fill up our form
$payment_id = $row['payment_id'];
$payment_supplier = $row['payment_supplier'];
$payment_ref = $row['payment_ref'];
$payment_cost_rating = $row['payment_cost_rating'];
$payment_amount = $row['payment_amount'];
}else{
echo "Unable to read record.";
}
}
var_dump ($stmt); prints
object(PDOStatement)#3 (1) { ["queryString"]=> string(157) "select payment_id, payment_supplier, payment_ref, payment_cost_rating, payment_amount from payments where payment_id = ? limit 0,1" }
But fetch() always returns false. This is the included database.php file if it helps
class Database{
// database credentials
private $host = "localhost";
private $db_name = "test-project";
private $username = "root";
private $password = "";
public $conn;
// get the database connection
public function getConnection(){
$this->conn = null;
try{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}}
What am I missing here?
The issue is with the fetch being used twice.
It can be done this way:
if($stmt->execute()){
//store retrieved row to a variable
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// display the row after fetching the contents.
var_dump($row);
//values to fill up our form
$payment_id = $row['payment_id'];
$payment_supplier = $row['payment_supplier'];
$payment_ref = $row['payment_ref'];
$payment_cost_rating = $row['payment_cost_rating'];
$payment_amount = $row['payment_amount'];
}else{
echo "Unable to read record.";
}
This should work well.
Add checking of execute result and see error:
if($stmt->execute()){
...
}else{
echo "Unable to read record:". print_r($stmt->errorInfo(), true);
}

PDO lastInsertId() returns 0

I've been looking, at other questions asking the same, and can't figure out why my query won't act like it should.
My query:
$stmt = db()->prepare("INSERT INTO conversations (user1, user2) VALUES (?, ?)");
$stmt->execute(array($_SESSION['user']['userId'], $user));
echo db()->lastInsertId();
When I do this the lastInsertId(); keeps returning 0.
My db() function:
function db()
{
$dsn = 'mysql:host=localhost;dbname=message_board';
$username = 'root';
$password = 'root';
try {
$db = new PDO($dsn, $username, $password);
} catch(PDOException $e) {
// exceptions handles here
}
return $db;
}
function db()
{
static $db;
$dsn = 'mysql:host=localhost;dbname=message_board';
$username = 'root';
$password = 'root';
if (!$db) {
$db = new PDO($dsn, $username, $password);
}
return $db;
}
You're creating a new db connection every line.
Try:
$db = db();
$stmt = $db->prepare("INSERT INTO conversations (user1, user2) VALUES (?, ?)");
$stmt->execute(array($_SESSION['user']['userId'], $user));
echo $db->lastInsertId();

MySql PHP Update Error

I've been messing about with this code for a few hours now and can't work out why it's not working. It's a profile update php page that is passed through JQuery and all seems to be fine except for it actually updating into the table. Here is the code I'm using:
session_start();
include("db-connect.php");//Contains $con
$get_user_sql = "SELECT * FROM members WHERE username = '$user_username'";
$get_user_res = mysqli_query($con, $get_user_sql);
while($user = mysqli_fetch_array($get_user_res)){
$user_id = $user['id'];
}
$name = mysqli_real_escape_string($con, $_REQUEST["name"]);
$location = mysqli_real_escape_string($con, $_REQUEST["location"]);
$about = mysqli_real_escape_string($con, $_REQUEST["about"]);
$insert_member_sql = "UPDATE profile_members SET id = '$user_id', names = '$name', location = '$location', about = '$about' WHERE id = '$user_id'";
$insert_member_res = mysqli_query($con, $insert_member_sql) or die(mysqli_error($con));
if(mysqli_affected_rows($con)>0){
echo "1";
}else{
echo "0";
}
All I get as the return value is 0, can anybody spot any potential mistakes? Thanks
To begin with, use
require("db-connect.php");
instead of
include("db-connect.php");
And now, consider using prepared statements, your code is vulnerable to sql injections.
Consider using PDO instead of the mysql syntax, in the long run I find it much better to use and it avoids a lot of non-sense-making problems, you can do it like this (You can keep it in the db-connect file if you want, and even make the database conncetion become global):
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$databaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host, $databaseName, $user, $pass);
Now, here's how you can solve your problem (Using prepared statements, avoiding sql injection):
function userId($db, $user_username)
{
$query = "SELECT * FROM members WHERE username = :username;";
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(
':username' => $user_username
));
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['user_id'];
}
return false
}
function updateProfile($db, $userId, $name, $location, $about)
{
$query = "UPDATE profile_members SET name = :name, location = :location, about = :about WHERE id = :userId;";
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':userId' => $userId,
':name' => $name,
':location' => $location,
':about' => $about
));
if($result)
{
return true;
}
return false
}
$userId = userId($db, $user_username); // Consider if it is not false.
$name = $_REQUEST["name"];
$location = $_REQUEST["location"];
$about = $_REQUEST["about"];
$updated = updateProfile($db, $userId, $name, $location, $about);
You should check the queries though, I fixed them a little bit but not 100% sure if they work.
You can easily make another function which inserts into tha database, instead of updating it, or keeping it in the same function; if you find an existance of the entry, then you insert it, otherwise you update it.

Categories