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();
Related
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);
}
in mainpage.php file, I use this:
<?php
$dsn = 'mysql:host=localhost;dbname=webfilter_schema';
$username = 'root';
$password = '';
$dbh = new PDO($dsn, $username, $password); //WORKS.
and its fine. But in another php file:
<?php
class HomeController {
public $pdoObject; // handle of the db connexion
private static $instance;
public function __construct()
{
$dsn = 'mysql:host=localhost;dbname=webfilter_schema';
$user = "root";
$password = "";
$this->$pdoObject = new PDO($dsn, $user, $password);// Error line..
}
public function createLocalObject(){
$query ="INSERT INTO USERS SET NAME = ?, PASSWORD = ?,IPADDRESS=?,E_MAIL=?";
$process = $this->pdoObject->prepare($query);
$insertResult = $process->execute(array("asd","ferfr","23","sadsads#hotmail.com"));
if($insertResult)
{
return true;
}
return false;
}
}
?>
it throws an exception like
Cannot access empty property in C:\xampp\htdocs\WP\Controller\HomeController.php5 on line 25
what is it happen ?
just added language as parameter..
public function __construct() {
$dsn = 'mysql:host=localhost;dbname=webfilter_schema';
$username = 'root';
$password = '';
$options = array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', );
$this->pdoObjectp = new PDO($dsn, $username, $password, $options);
}
and it works.
What I want is to return MYSQL query in a array however my code returns a bool(true).
Here is the code from code.php
require('model.php');
$id = $_POST['id'];
$password = $_POST['password'];
$user = new user();
$row = $user->check_user($id, $password);
var_dump($row);
Here is the code from model.php
class config {
public $dbhost = "localhost";
public $dbuser = "root";
public $dbpass = "";
public $dbused = "dbname";
function dbconn() {
$conn = mysqli_connect($this->dbhost,$this->dbuser,$this->dbpass,$this->dbused);
if(mysqli_connect_errno()) {
printf("Connection failed: " . mysqli_connect_error());
exit();
}
return $conn;
}
}
class user {
function check_user($id, $pass) {
$config = new config();
$conn = $config->dbconn();
$query = $conn->prepare("SELECT id, password, status FROM e_users WHERE id = ? AND password = ?");
$query->bind_param('is', $id, $pass);
try {
$query->execute();
return $query->fetch();
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
I think the problem is in the $query->fetch(); because I tried return 'test'; and it works fine. Even return an array works fine.
Can anyone help me?
As The Blue Dog pointed out, fetch() returns a status flag, not the row itself. But fetch_assoc() will return a row.
Have a look here:
http://php.net/manual/en/mysqli-stmt.fetch.php
If you work with fetch, you need to bind the variables:
$stmt->bind_result($mySelectedValue_1, $mySelectedValue_2);
Here are examples with fetch_assoc():
http://php.net/manual/de/mysqli.quickstart.prepared-statements.php
So this should work fine:
$row = $res->fetch_assoc();
Im trying to create a user management section on my website that allows users to login.
So far I have the following PDO Conenction class...
<?php
class connection{
private $host = 'localhost';
private $dbname = 'dbname';
private $username = 'liam#';
private $password ='Password';
public $con = '';
function __construct(){
$this->connect();
}
function connect(){
try{
$this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'We\'re sorry but there was an error while trying to connect to the database';
file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND);
}
}
}
?>
My check-login.php looks like...
<?php
include 'assets/connection.class.php';
$username=$_POST['username'];
$password=$_POST['password'];
function login(PDO $db, $username, $password) {
$user_id = user_id_from_username($db, $username);
$password = md5($password);
$stmt = $db->prepare('SELECT COUNT(`user_id`) FROM `users` WHERE `username` = ? AND `password` = ?');
$stmt->bindParam(1, $username);
$stmt->bindParam(2, $password);
$stmt->execute();
if($stmt->fetchColumn() > 0) {
return $user_id;
} else {
return false;
echo 'failed';
}
}
?>
my problem is that im not given any result from check-login.php? Im not a php programmer so apologies if this seems vague, any help will be appreciated
It could be a problem with
$user_id = user_id_from_username($db, $username);
Since we don't know what that function (user_id_from_username) is doing, it might be that the
return $user_id;
is just returning NULL or an empty string.
I have this in db.php page:
function db_connect(){ $link = new mysqli(localhost, user, pass, table); }
And this is in other page:
require_once("db.php");
function register($username, $email, $password){
global $link;
$query = "INSERT INTO proyecto.user (username, password, email)
VALUES ('$username', '$password', '$email')";
$result = mysqli_query($link, $query);
}
But it doesn't work when I call "register". How should I call the function "db_connect"?
You can do it like this (PDO connection):
// 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); // You can make it be a global variable if you want to access it from somewhere else.
You can make it become a global variable if you want.
$GLOBALS['db'] = $db;
Note that this is pdo, an example of a PDO database operation for your case, note that this uses prepared statements and is therefor quite safe from sql injections, and is quite easy to use:
function register($username, $email, $password){
$query = "INSERT INTO user (username, password, email) VALUES (:username, :password, :email)"; // Construct the query, making it accept a prepared variable search.
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':username' => $username,
':password' => $password,
':email' => $email
)); // Here you insert the variable, by executing it 'into' the prepared query.
if($result)
{
return true;
}
return false
}
And you can call it like this:
$registerSuccess = register($username, $email, $password);
have db_connect() return the $link, or make $link global in db_connect()
function db_connect() {
return new mysqli(localhost, user, pass, table);
}
function register($username, $email, $password) {
$link = db_connect();
$query = "INSERT INTO proyecto.user (username, password, email)
VALUES ('$username', '$password', '$email')";
$result = mysqli_query($link, $query);
}