I Have a Problem With Source Code PHP PDO . I Try make a CRUD with PHP PDO , but when i try source code for delete and when I run a script the Data do not want to be erased .. I apologize if my speaking was nothing wrong, I am from Indonesian
Thank's Before
Script function delete :
public function deleteData($id)
{
// fungsi menghapus data dari database
$this->id = $id;
$this->sql = "DELETE FROM student WHERE id=:id";
$this->q = $this->dbh->prepare($sql);
$this->q->bindParam(":id",$this->id);
$this->q->execute();
return true;
}
Script delete.php
<?php
include "belajar_crud.php";
$obj = new crud;
$id = isset($_GET['id']) ? $_GET['id']:'';
$obj->deleteData($id);
?>
Change this line:
$this->q = $this->dbh->prepare($sql);
Into this:
$this->q = $this->dbh->prepare($this->sql);
This is the only error I see in the code...
If this is not the case, you need to provide more information.
why you no try this?
config.php:
define('HOST','your host');
define('BD','your database');
define('USER','your user');
define('PASS','your password');
BD.class.php:
class BD{
private static $conn;
public function __construct(){}
public function conn(){
if(is_null(self::$conn)){
self::$conn = new PDO('mysql:host='.HOST.';dbname='.BD.'',''.USER.'',''.PASS.'');
}
return self::$conn;
}
}
your code of delete:
#BD::conn();
$query = #BD::conn()->prepare("DELETE FROM YOURTABLE WHERE ID = ?");
if($query->execute(array($this->id))){
echo "<script>alert('Delete Successful');</script>";
}
Related
What I want is to get and store the last inserted ID, but I am not sure how. The scenario is, after a user add a record he/she will be redirected to a page that will show him/her of the summary of what he/she saved. But I am not sure how I can do that, to retrieved the recently added record.
I have a class which look like this record.php
<?php
class Record {
private $conn;
private $table_name_1 = "name_of_the_table_1";
private $table_name_2 = "name_of_the_table_2";
public $name;
public $age;
public function __construct($db){
$this->conn = $db;
}
function newRecord(){
$query = "INSERT INTO " . $this->table_name_1 . " SET name=:name;
INSERT INTO " . $this->table_name_2 . " SET age=:age";
$stmt = $this->conn->prepare($query);
$this->name=$this->name;
$this->age=$this->age;
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':age', $this->age);
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
?>
now I have another php form that create and add record, the code is something like this add_record.php
<?php
inlude_once 'db.php'
inlude_once 'record.php'
$database = new Database();
$db = $database->getConnection();
$record = new Record($db);
?>
<?php
if($_POST) {
$record->name=$_POST['name'];
$record->age=$_POST['age'];
if(record->record()){
header("Location:{$home_url}view_recently_added_record.php?action=record_saved");
}
else{
echo "Unable to save";
}
}
?>
The idea is to save the query to two different table and the same time automatically record the auto increment ID of table 1 to table 2 so that they have a relationship. I am thinking I can do that if I can store immediately the ID from table 1 and assigned it a variable maybe so it can be automatically saved to table two using a new query or function maybe. Is this possible? does it make sense? and another thing I wanted to display the recently recorded data immediately to the user. Thank you.
You can return $stmt->insert_id or -1 insteaf of boolean in the newRecord function:
function newRecord(){
...
if($stmt->execute()){
return $stmt->insert_id;
}else{
return -1;
}
}
and use the value to redirect like this:
$newrecord = record->newRecord();
if($newrecord != -1) {
header("Location:{$home_url}view_recently_added_record.php?action=record_saved&id=".$newrecord);
}
else{
echo "Unable to save";
}
this may be a stupid question, but every source on the web seems not able to fully explain the logic to my complex brain
There's an edit page getting a $_GET['id'] from a link.
I got a function on my class elaborating this one to create an array of values from the database which must fill the form fields to edit datas. The short part of this code:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from anammi.anagrafica WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
This array (which i tried to print) is perfectly ready to do what i'd like.
My pain starts when i need to pass it to the following function in the same class, which perhaps calls a parent method to print the form:
public function Associa() {
$a = $this->EditDb();
$this->old_id = $a['old_id'];
$this->cognome = $a['cognome'];
$this->nome = $a['nome'];
$this->sesso = $a['sesso'];
$this->tipo_socio_id = $a['tipo_socio_id'];
$this->titolo = $a['titolo']; }
public function Body() {
parent::Body();
}
How do i have to pass this $fetch?
My implementation:
<?php
require_once '/classes/class.ConnessioneDb.php';
require_once '/classes/class.editForm';
$edit = new EditForm();
$edit->prel();
if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();
if (if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();) {
$edit->Associa();
$edit->Body();
your Editdb method is returning a string and you are checking for a boolean condition in if statement. this is one problem.
using fetch-
$fetch=$edit->EditDb();
$edit->Associa();
$edit->Body($fetch);
Posting the full code of it:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from table WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
public function Associa($fetch) {
$this->old_id = $fetch['old_id'];
$this->cognome = $fetch['cognome'];
$this->nome = $fetch['nome'];
$this->sesso = $fetch['sesso']; //it goes on from there with many similar lines
}
public function Body() {
$body = form::Body();
return $body;
}
Implementation
$edit = new EditForm();
$edit->prel();
$fetch=$edit->EditDb();
$edit->Associa($fetch);
$print = $edit->Body();
echo $print;
Being an edit form base on a parent insert form, i added an if in the parent form that sees if is set an $_GET['id] and prints the right form header with the right form action. This was tricky but really satisfying.
Method in my class does it work properly. Don't give me some error message, but simply does not work.
public function query($value)
{
$this->__error = FALSE;
$sql = "SELECT * FROM users WHERE username = ".Input::input($value);
if ($this->__query = $this->__pdo->query($sql))
{
$this->__result = $this->__query->fetchAll(PDO::FETCH_OBJ);
$this->__count = $this->__query->rowCount(); //Here is the problem
}
else {
$this->__error = TRUE;
}
return $this;
}
public function count()
{
return $this->__count;
}
But I would not write whole class code, I mention that PDO DataBase connection is properly defined ($_pdo property), also the instance who is responsible to comunicate with database. ($_instance property). Input class too.
Here is my index.php (some kind of registration form):
<?php
spl_autoload_register(function($class) //Load all class in project
{
require_once 'class/'.$class.'.php';
}
);
$user = DataBase_class::instance()->query("username"); //username is the name of textbox
if ($user->count())
{
echo 'User exist';
}
else echo 'User not exist';
?>
Result is "User not exist", although user exist 100%.
You forget the quotes
$sql = "SELECT * FROM users WHERE username = '".Input::input($value) . "'";
but you should consider to use prepared statements..
$stmt = $this->__pdo->prepare("SELECT * FROM users WHERE username = :name");
$stmt->bindParam(':name', Input::input($value));
$result = $stmt->execute();
I have written a php class to use in a small script to just run any query that I like from other scripts. This is NOT going to be used publicly or in production, and I'm aware of the huge security issue this poses!
I have done this as an excercise to see learn about classes etc... I seem to be having problems with one specific line in the code which is causing an error somewhere. I think it might be because I'm trying to return an array, and I think I haven't defined it properly in the class.
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC));
This is the whole code.
<?php
class GetRandomRecord {
//Connection
public $CUDBName;
public $CUHost;
public $CUUser;
public $CUPassword;
public $in_SQL;
public $out_Resource;
public $CULink;
public $message;
public $errors = array(); // is this correct?
public $resultOfQuery = array(); // is this correct?
/****************************************************************/
public function setSQL($value){
$this->in_SQL = $value;
return $this->in_SQL;
}
/****************************************************************/
public function setConnectionString($db,$host,$user,$password){
$this->CUDBName = $db;
$this->CUHost = $host;
$this->CUUser = $user;
$this->CUPassword = $password;
}
/****************************************************************/
public function runSQL() {
$this->CULink = mysqli_connect( $this->CUHost , $this->CUUser , $this->CUPassword , $this->CUDBName);
if (mysqli_connect_errno()) {
$this->message = "Connection failed: ".mysqli_connect_error();
return $this->message;
}
$this->out_Resource = mysqli_query($this->in_SQL , $this->CULink);
if (!$this->out_Resource)
{
$this->errors['sql'] = $this->in_SQL;
$this->errors['eeDBName'] = $this->CUDBName;
$this->errors['eeLink'] = $this->CULink;
$this->errors['status'] = "false"; //There was a problem saving the data;
mysqli_close($this->CULink);
return json_encode($this->errors);
}
else
{
// success
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC));
mysql_close($this->CULink);
return $this->resultOfQuery;
} // if (!mysql_query( $CUDBName , $sql , $CULink))
}
/****************************************************************/
}//class
$recordGet = new getRandomRecord();
$recordGet->setConnectionString('databasename','localhost','username','password');
// select count from database
$tableName = "userList";
$countSQL = "select count(*) from $tableName";
$recordGet->setSQL($countSQL);
$result = $recordGet->runSQL();
print_r($result);
?>
Can you help me identify the problem?
EDIT: Actually I haven't got a specific error message. I have an HTTP Error 500 which usually means my code is duff, and I narrowed it down by commenting sections of code until I found the line that caused it.
You have an extra close-paren on line 64.
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC));
The line should be:
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC);
I have been turning and twisting this to the best of my non-existing PDO knowledge, but still without any luck.
the code:
function write($id, $data) {
global $dbcon;
$id = mysql_real_escape_string($id);
$data = mysql_real_escape_string($data);
$sql = $dbcon->exec("INSERT INTO `sessions`
(`session_id`, `session_data`,
`session_expire`, `session_agent`,
`session_ip`, `session_referrer`)
VALUES
(\"".$id."\", \"".$data."\",
\"".time()."\",\"".($this->session_encryption($_SERVER['HTTP_USER_AGENT']))."\",
\"".($this->session_encryption($_SERVER['REMOTE_ADDR']))."\", \"".($this->session_encryption((isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_^~#&|=+;!,(){}[].?%*#'))))."\")
ON DUPLICATE KEY UPDATE
`session_data` = \"".$data."\",
`session_expire` = \"".time()."\"");
return true;
}
Give me the following error:
Fatal error: Call to a member function exec() on a non-object
on the
$sql = $dbcon->exec(
line.
I have been trying to solve this all evening, but without any luck.
This is my PDO connection script:
require_once(INC_PATH.'/config.php');
$dsn = "$db_type:host=$db_host;port=$db_port;dbname=$db_name;charset=$db_charset";
try{
$dbcon = new PDO($dsn, $db_user, $db_pass);
$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$dbcon = null; //Close database connection.
}
catch(PDOException $e){
echo $e->getMessage();
}
Hope one of you kind souls out there can help me, I would deeply appreciate it!
Thanks.
UPDATE:
I have a global.php file which looks like this:
//Load database
require_once(INC_PATH.'/database.php');
//Load session handler
require_once(INC_PATH.'/class_sessions.php');
$Sessions = new SessionManager();
session_start();
The database.php is included before the sessions class, and when I view the website, it does not give any errors on this part of the sessions class (which is before the write function:
function read($id) {
global $dbcon;
$data = '';
$id = mysql_real_escape_string($id);
$sql = $dbcon->prepare("SELECT
`session_data`
FROM
`sessions`
WHERE
`session_id` = '".$id."'");
$sql->execute();
$a = $sql->columnCount();
if($a > 0) {
$row = $sql->fetchObject();
$data = $row['session_data'];
}
return $data;
}
Are you sure your connection script is getting executed? Try checking if $dbcon is set. Also, you may be missing global $dbcon within the connection script.
By the way, since you're already using PDO, might I recommend you use placeholders in your query:
$sql = "INSERT INTO `sessions`
(`session_id`, `session_data`, `session_expire`,
`session_agent`, `session_ip`, `session_referrer`)
VALUES
(:session_id, :session_data, :session_expire,
:session_agent, :session_ip, :session_referrer)
ON DUPLICATE KEY UPDATE
`session_data` = :session_data,
`session_expire` = :session_expire";
$params = array(
':session_id' => $id,
':session_data' => $data,
':session_expire' => time(),
':session_agent' => $this->session_encryption($_SERVER['HTTP_USER_AGENT']),
':session_ip', => $this->session_encryption($_SERVER['REMOTE_ADDR']),
':session_referrer' => $this->session_encryption((isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_^~#&|=+;!,(){}[].?%*#';
);
$stmt = $dbcon->prepare($sql);
if ($stmt->execute($params) === FALSE) {
// handle error
}
First check that the global object is not being overwritten by another function. I strongly suggest you use Dependency injection instead of globals.
$Sessions = new SessionManager($dbcon);
And inside the Session Management class you can do something like
class SessionManager
{
protected $db;
public function __construct($db) { $this->db = $db; }
public function read($id)
{
$stmt = $this->db->prepare("SELECT session_data
FROM sessions
WHERE session_id = ?");
$stmt->execute(array($id));
return $stmt->fetchColumn();
}
}
And secondly, since you are using PDO, you dont need to call mysql_real_escape_string(), use prepared statements and placeholders :)