I need your help figuring this out. I am trying to have a reserve a book functionality in my project. I don't have any error with this one but my oop functions that contains the pdo statements won't work. Particulary with the insert (values can't be inserted into the database) and update(can't update existing info from the database) part. I don't know why this happens.
bookReserve.php
<?php
session_start();
include_once "../styles/header-menu-out.php";
include_once "dbconnection.php";
function __autoload($class){
include_once("../main/".$class.".php");}
$code = new codex_books();
$sname = $_POST['sname'];
$sid = $_POST['sid'];
$id = $_POST['id'];
$title = $_POST['title'];
$author = $_POST['author'];
$isbn = $_POST['isbn'];
$publisher = $_POST['publisher'];
$language = $_POST['language'];
$genre = $_POST['genre'];
$quantity = $_POST['quantity'];
$date_to_be_borrow = $_POST['date_to_be_borrow'];
$result = $code->bookreserve($id,"book_info");
if(isset($_POST['reserve']))
{
foreach($result as $row)
{
echo $oldstock=$row['quantity'];
}
echo $newstock = $oldstock-1;
$code->minusbookreserve($quantity, $newstock,"book_info");
$code->insertbookreserve($sid,$sname,$title,$author,$isbn,$publisher,$language,$genre,$quantity,$date_to_be_borrow,"reserve_list");
// echo "<script type='text/javascript'>alert('Successfully Reserved.');window.location='bookReservelist.php';</script>";
}
else {
echo "<script type='text/javascript'>alert('Something went wrong.');window.location='bookReservelist.php';</script>";
}
?>
codex_books.php
public function minusbookreserve($quantity, $newstock, $table)
{
$q = "UPDATE $table SET quantity = ':newstock' where book_title = ':book_title'";
$stmt = $this->con->prepare($q);
$stmt->execute(array(':newstock'=>$newstock, ':quantity'=>$quantity));
if($stmt){
return true;
}
else {
return false;
}
}
public function insertbookreserve($sid,$sname,$title,$author,$isbn,$publisher,$language,$genre,$quantity,$date_to_be_borrow,$table)
{
$q = "INSERT INTO $table SET sid= :sid ,sname=:sname,title=:title,author=:author,isbn=:isbn,publisher=:publisher,language=:language, genre=:genre, quantity=:quantity, date_to_be_borrow=:date_to_be_borrow";
$stmt = $this->con->prepare($q);
$stmt->execute(array(':sid'=>$sid,':sname'=>$sname,':title'=>$title,':author'=>$author,':isbn'=>$isbn,':publisher'=>$publisher,':language'=>$language, ':genre'=>$genre,':quantity'=>$quantity,':date_to_be_borrow'=>$date_to_be_borrow));
return true;
}
Given:
$q = "UPDATE $table SET quantity = ':newstock' where book_title = ':book_title'";
^^^^^^^^^^^
Where's book_title here?
$stmt->execute(array(':newstock'=>$newstock, ':quantity'=>$quantity));
You really MUST check return values from your DB calls for boolean FALSE, indicating failure. You're simply assuming everything will always succeed, which is a very BAD way of writing code.
Related
AIM
I am attempting to update SQL.
I suspect that the issue is either with my sql query, or with my connection. Although, I could be totally wrong.
Apologies if it's messy, but I'm using console.log to attempt to debug the issue, and the console output is:
B.1
B.2
D.1
D.2
D.3
B.2.1
B.5
In relation to sql queries, amongst others, I've attempted with the following two:
$sql = "UPDATE Users SET description = " . '$description' . "WHERE userID = " . '$this->userID';
$sql = "UPDATE Users SET description = '$description' WHERE userID = '$this->userID'";
CODE
edit-profile-handler.php
<?php
if(isset($_POST['edit-profile-button'])) {
$description = $_POST['edit-description'];
echo '<script>console.log("B.1")</script>';
if(isset($description)) {
echo '<script>console.log("B.2")</script>';
$result = $user->updateDescription($description);
echo '<script>console.log("B.2.1")</script>';
}
if($result == true) {
echo '<script>console.log("B.4")</script>';
header("Location: profile.php");
}
echo '<script>console.log("B.5")</script>';
}
?>
User.php
<?php
class User {
private $con;
private $userID;
private $description;
public function __construct($con, $userID) {
$this->con = $con;
$this->userID = $userID;
$sql = "SELECT * FROM Users WHERE userID='$this->userID'";
$query = mysqli_query($this->con, $sql);
$user = mysqli_fetch_array($query);
$this->description = $user['description'];
}
public function getID() {
return $this->userID;
}
public function updateDescription($description) {
echo '<script>console.log("D.1")</script>';
$sql = "UPDATE Users SET description = '$description' WHERE userID = '$this->userID'";
echo '<script>console.log("D.2")</script>';
$result = mysqli_query($this->con, $sql);
echo '<script>console.log("D.3")</script>';
return $result;
echo '<script>console.log("D.4")</script>';
}
}
?>
Your $result variable is not returning a BOOLEAN because it handles an UPDATE query result.
So on your updateDescription function, try to return mysqli_affected_rows() then try to check on edit-profile-handler.php if $return > 0 it means there are row/s affected by your update. You can refer here.
I would like to pass the properties to a function to Update details in a database. I want all the columns that were selected in the form to be passed to a function. Frankly, I don't know what to do.
My code is the following:
if (isset($_POST["updateWineButton"])) {
$wineID = $_POST["wineID"];
$wineCountryID = $_POST["wineCountryID"];
$wineSizeID = $_POST["wineSizeID"];
$wineRatingID = $_POST["wineRatingID"];
$wineColourID = $_POST["wineColourID"];
$packageID = $_POST["packageID"];
$wineCategoryID = $_POST["wineCategoryID"];
$wineCode = $_POST["wineCode"];
$price = $_POST["price"];
$description = $_POST["description"];
$wineRating = $_POST["wineRating"];
$wineIMG = $_POST["wineIMG"];
updateWine($updateWine);
$status = "$description has been updated.";
}
Update Wine Function
function updateWine($wineUpdate)
{
global $pdo;
$statement = $pdo->prepare("UPDATE WINE SET wineID=?, wineCountryID=?, wineSizeID=?, wineRatingID, wineColourID=?,
packageID=?, wineCategoryID=?, wineCode=?, price=?, description=?, wineRating=?, wineIMG=?
WHERE wineID=?");
$statement->execute([$wineUpdate->wineID,
$wineUpdate->wineCountryID,
$wineUpdate->wineSizeID,
$wineUpdate->wineRatingID,
$wineUpdate->wineColourID,
$wineUpdate->packageID,
$wineUpdate->wineCategoryID,
$wineUpdate->wineCode,
$wineUpdate->price,
$wineUpdate->description,
$wineUpdate->wineRatingID,
$wineUpdate->wineIMG]);
$statement->fetch();
}
Something like the following should work for you:
function updateWine()
{
global $pdo;
$keys = [
"wineID", "wineCountryID", "wineSizeID", "wineRatingID", "wineColourID", "packageID", "wineCategoryID",
"wineCode", "price", "description", "wineRating", "wineIMG",
];
$results = [];
foreach ($keys as $index) {
if (isset($_POST[$index])) {
$results[$index] = $_POST[$index];
}
}
$statement = $pdo->prepare("UPDATE WINE SET " . implode('=?, ', array_keys($results)) . "=? WHERE wineID =?");
$statement->execute(array_merge(array_values($results), [$_POST['wineID']]));
$statement->fetch();
}
if (isset($_POST["updateWineButton"]) && isset($_POST['wineID'])) {
updateWine();
}
Hope this helps!
if I understand correctly you want to do something like this,
if (isset($_POST["updateWineButton"])) {
$result = updateWine($_POST);
if($result){
$status = "$description has been updated.";
}else{
$status = "An error occurred.";
}
}
//your function woud then look like ...
function updateWine($postdata){
$wineID = $postdata["wineID"];
$wineCountryID = $postdata["wineCountryID"];
$wineSizeID = $postdata["wineSizeID"];
$wineRatingID = $postdata["wineRatingID"];
$wineColourID = $postdata["wineColourID"];
$packageID = $postdata["packageID"];
$wineCategoryID = $postdata["wineCategoryID"];
$wineCode = $postdata["wineCode"];
$price = $postdata["price"];
$description = $postdata["description"];
$wineRating = $postdata["wineRating"];
$wineIMG = $postdata["wineIMG"];
//udpate your database with the above values
//check if update is successful
return true;
//else if there was an error
return false;
}
At the end of this code there is a INSERT INTO statement that doesn't do anything. My connection.php is OK because I have used the same file in other projects and they work.
I am actually inserting a lot more data, but I was trying to find the problem out so I've removed a lot of variable from the INSERT statement.
<?php
include("connection.php");
include("functions.php");
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
date_default_timezone_set('Asia/Dhaka');
$mobile = (string)$_GET["mobile_number"];
$promo = (string)$_GET["promo_code"];
$type = (string)$_GET["type"];
$type_no = (($type=="imei") ? (string)$_GET["imei"] : (string)$_GET["udid"]);
$ip = (string)$_SERVER['REMOTE_ADDR'];
$signup_date = date("Y-m-d");
$q1 = "SELECT * FROM vbClient WHERE clCustomerID = :mobile";
$chk_mob_switch = $dbh->prepare($q1);
$chk_mob_switch->bindParam(':mobile', $mobile);
$chk_mob_switch->execute();
if ($chk_mob_switch->rowCount() == 0) {
$q2 = "SELECT * FROM api_db WHERE type_no = :type_no";
$chk_imei_bknd = $dbh->prepare($q2);
$chk_imei_bknd->bindParam(':type_no', $type_no);
$chk_imei_bknd->execute();
if ($chk_imei_bknd->rowCount() == 0) {
$validation_code = (string)generateValidationCode(6);
$request_id = (string)generateRequestID(15);
$q3 = "INSERT INTO api_db (mobile) VALUES (:mobile)";
$ins_info_bknd = $dbh->prepare($q3);
$ins_info_bknd->bindParam(':mobile', $mobile);
$ins_info_bknd->execute();
}
To check for errors I am using a function like the following:
function chkSyntax($dbh, $stmt, $query) {
$stmt = $dbh->prepare($query);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
}
And then I'm calling it like this:
chkSyntax($dbh, $chk_mob_switch, $q1);
What am I doing wrong?
So I've been stuck on this for quite a while, surprisingly the update and delete functions work just fine, however I cannot make the CREATE function work properly. Please have a look at it and tell me what I'm doing wrong
<-------------- Entire model for admin panel-------------->>>>>>>> Connection to DB is working fine---------->>>>>>>>>>>
<?php
include_once "Model.php";
class ModelPages extends Model {
public function get($key) {
$sql = "SELECT * from pages where page_key = '$key'";
$row = '';
$page = Null;
foreach ($this->pdo->query($sql) as $row) {
$page = $row;
}
// echo "<pre>";
// var_dump($page);
// exit;
return $page;
}
public function getAll() {
$statement = $this->pdo->prepare("SELECT * from pages Where Id > 3");
$result = $statement->execute();
$pages = array();
if($result) {
$pages = $statement->fetchAll(PDO::FETCH_ASSOC);
}
return $pages;
}
public function updatePage($params=array()) {
if (!is_array($params)) {
return 'Params should be an array';
}
if (isset($params['table'])) {
$tableName = $params['table'];
} else {
$tableName = 'pages';
}
$pageId = isset($params['page_key']) ? $params['page_key'] : null;
$pageTitle = isset($params['page_title']) ? $params['page_title'] : null;
$pageBody = isset($params['page_body']) ? $params['page_body'] : null;
if ($pageId == null) {
return 'No page id provided';
}
$sql = "UPDATE " . $tableName . " SET
title = :title,
body = :body
WHERE page_key = :page_key";
$statement = $this->pdo->prepare($sql);
$statement->bindParam(':title', $pageTitle, PDO::PARAM_STR);
$statement->bindParam(':body', $pageBody, PDO::PARAM_STR);
$statement->bindParam(':page_key', $pageId, PDO::PARAM_INT);
$result = $statement->execute();
return $result;
}
public function deletePage($pageId) {
// build sql
$sql = "DELETE FROM pages WHERE id = " . intval($pageId);
$statement = $this->pdo->prepare($sql);
$result = $statement->execute();
return $result;
}
public function createPage($params=array()){
if (!is_array($params)) {
return 'Params should be an array';
}
if (isset($params['table'])) {
$tableName = $params['table'];
} else {
$tableName = 'pages';
}
$page_key = isset($params['page_key']) ? $params['page_key'] : 'page_key';
$pageTitle = isset($params['page_title']) ? $params['page_title'] : 'page_title';
$pageBody = isset($params['page_body']) ? $params['page_body'] : 'page_body';
$sql = "INSERT INTO " . $tablename ." SET page_key=:page_key, title=:title, body=:body ";
// prepare query for execution
$statement = $this->pdo->prepare($sql);
// bind the parameters
$statement->bindParam(':page_key', $_POST['page_key']);
$statement->bindParam(':title', $_POST['title']);
$statement->bindParam(':body', $_POST['body']);
// specify when this record was inserted to the database
// Execute the query
$result = $statement->execute();
return $result;
}
}
<?php
include 'controllers/controller.php';
include 'models/Model.php';
include 'models/ModelPages.php';
<------------------------ADMIN CONTROller----------------------->>>>>>>>>>>>
class Admin extends Controller {
function __construct() {
// create an instance of ModelPages
$ModelPages = new ModelPages();
if(isset($_POST['page_key'])) {
// TODO: update DB
$tableData['page_body'] = $_POST['body'];
$tableData['table'] = 'pages';
$tableData['page_title'] = $_POST['title'];
$tableData['page_key'] = $_POST['page_key'];
$response = $ModelPages->updatePage($tableData);
if ($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&success=true");
}
}
if(isset($_GET['page_key'])) {
// by default we assume that the key_page exists in db
$error = false;
$page = $ModelPages->get($_REQUEST['page_key']);
// if page key does not exist set error to true
if($page === null) {
$error = true;
}
// prepare data for the template
$data = $page;
$data["error"] = $error;
// display
echo $this->render2(array(), 'header.php');
echo $this->render2(array(), 'navbar_admin.php');
echo $this->render2($data, 'admin_update_page.php');
echo $this->render2(array(), 'footer.php');
} else {
// case: delete_page
if(isset($_GET['delete_page'])) {
$response = $ModelPages->deletePage($_GET['delete_page']);
if($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&deleted=true");
}
}
}
//Get table name and make connection
if(isset($_POST['submit'])) {
$page_key = $_POST['page_key'];
$page_title = $_POST['title'];
$page_body = $_POST['body'];
$response = $ModelPages->createPage();
if($response=TRUE){
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&created=true");
}
}
}
// load all pages from DB
$pages = $ModelPages -> getAll();
// display
echo $this->render2(array(), 'header_admin.php');
echo $this->render2(array(), 'navbar_admin.php');
echo $this->render2(array("pages"=> $pages), 'admin_view.php');
echo $this->render2(array(), 'footer.php');
}
}
?>
Since you have if(isset($_POST['page_key']) on the top:
class Admin extends Controller {
function __construct() {
// create an instance of ModelPages
$ModelPages = new ModelPages();
if(isset($_POST['page_key'])) {
...
if ($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?
}
and it is used to call $response = $ModelPages->updatePage($tableData);
your code never reach the part with good values at the bottom:
if(!isset($_POST['page_key'])) {
...
$response = $ModelPages->createPage($tableData);
So my simple but not the best suggestion is use extra parameter when POST like action. so you can check:
if(isset($_POST['action']) && $_POST['action']=='update') {
...
} elseif (isset($_POST['action']) && $_POST['action']=='create') {
...
} etc...
hope this will help you for now :-)
$sql = "INSERT INTO " . $tablename ." SET page_key=:page_key, title=:title, body=:body ";
$tablename is not in scope when the statement above is executed. And you've got no error handling in the code.
I am trying to use a variable from my function in an echo in PHP for a form. This is an update form so I want to display current user informatoin.
My function is like this:
public static function current()
{
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
$pdo = Database::connect();
$sql = "SELECT * FROM customer where counter = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$firstname = $data['firstname'];
$lastname = $data['lastname'];
$email = $data['email'];
Database::disconnect();
}
my form is trying to echo it here in the value:
<input class="form-control" name="firstname" id="firstname"
value="<?php echo !empty($firstname)?$firstname:'';?>">
I can't seem to get the $firstname variable to echo the users first name. The user is called by a string in the url that uses ?id=
Two options,
return the desired value (or values) from the function
public static function current()
{
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
$pdo = Database::connect();
$sql = "SELECT * FROM customer where counter = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
Database::disconnect();
return array_intersect_key($data, array_flip(array('firstname', 'lastname', 'email')));
}
...
$user = Thing::current();
echo $user['email'];
OR set a static variable in your class to reference after
public static function current()
{
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
$pdo = Database::connect();
$sql = "SELECT * FROM customer where counter = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
self::$firstname = $data['firstname'];
self::$lastname = $data['lastname'];
self::$email = $data['email'];
Database::disconnect();
}
...
echo Thing::$firstname;
I'd prefer the first thing, but instead of returning an array with the details, make it into a Customer object.