PHP SQL update query - php

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.

Related

isset invocation gets last variable value

I have a PHP class called Question. Inside Question is a public variable called $q_id.
class Question{
public $url;
public $q_id;
function __construct(){
global $db;
$this->url = $_GET["url"];
$result = $db->query("SELECT q_id FROM wyr_questions WHERE `url` = '$this->url'");
if ($result->num_rows == 0){
header('Location: 404');
die();
}
else{
$row = $result->fetch_array();
$this->q_id = $row["q_id"];
}
}
$user = new Question();
Now I have 2 buttons, a dislike and a like button. When the user presses the like or dislike button, a $_POST method is invoked. The isset method is outside of the class and underneath the $user object.
if (isset($_POST["like"])){
$q_id = $user->q_id;
if ($_POST["like"] == 1){
$db->query("UPDATE wyr_questions SET thumbs_up = thumbs_up + 1 WHERE `q_id` = '$user->q_id'");
}
else{
$db->query("UPDATE wyr_questions SET thumbs_down = thumbs_down+1 WHERE `q_id` = '$q_id'");
}
}
Now every time I click the like button, the number of likes are updated based on what the last q_id was. For example, let's say I liked q_id: 29 and then moved to like q_id: 30 then the query in isset($_POST["like"]) will update the number of likes for q_id: 29 and not q_id: 30 Why is it updating the previous q_id and not the current q_id?
Just move your code
$user = new Question();
inside the isset invocation.
something like this:
class Question{
public $url;
public $q_id;
function __construct(){
global $db;
$this->url = $_GET["url"];
$result = $db->query("SELECT q_id FROM wyr_questions WHERE `url` = '$this->url'");
if ($result->num_rows == 0){
header('Location: 404');
die();
}
else{
$row = $result->fetch_array();
$this->q_id = $row["q_id"];
}
}
if (isset($_POST["like"])){
$user = new Question(); //here is the new position of this code
$q_id = $user->q_id;
if ($_POST["like"] == 1){
$db->query("UPDATE wyr_questions SET thumbs_up = thumbs_up + 1 WHERE `q_id` = '$user->q_id'");
}
else{
$db->query("UPDATE wyr_questions SET thumbs_down = thumbs_down+1 WHERE `q_id` = '$q_id'");
}
}

How to use php functions in IF statement

INTRO
I am trying to better understand my knowledge of Php and using classes to better prganise my code so this is just an exercise for a better understanding rather than a real world solution.
BRIEF
I am calling in a function from a class which I have just learnt to do but I want to know the best way to do something simple tasks like use the object in an IF statement.
SCENARIO
So for instance I am setting my classes like so:
class user
{
// Get users ID
function get_user_id()
{
global $conn;
$sql = 'SELECT id FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['id'] . ', '; }
}
}
// Get users name
function get_user_name()
{
global $conn;
$sql = 'SELECT name FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['name'] . ', '; }
}
}
}
$userId = new user;
$userName = new user;
I am then initializing in my classes like so:
<?php $userId->get_user_id(); ?>
<?php $userName->get_user_name(); ?>
and THEN I am wanting to performa simple task like show a user based on the value of their ID, the above will return 2 sets of results of 4 so id 1, 2, 3, 4 & Dan, Andy, Ryan, Aran
so I am performing a simple IF statement like so:
if($userId > 1){
echo $userName;
} else {
echo 'not working';
}
But it returns 'not working' - I am just wanting to better understand how to use the functions in a way that A works and B best practice.
It doen't look like you've understood OOP just yet.
These code examples should hopefully give you an introduction but as in other comments, read up on OOP. I struggled with it at first but keep at it!
Create your user class
This class represents a single user and the actions associated with a user, think of it as a blue print. It should only perform functions related to a user, it shouldn't keed to 'know' about anything else. For example, database functions sholud be done elsewhere.
class User {
private $id;
private $name;
function __construct($array)
{
$this->id = $array['id'];
$this->name = $array['name'];
}
function getId()
{
return $this->id;
}
function getName()
{
return $this->name;
}
}
Load all users into an array
$sql = 'SELECT * FROM user';
$result = $conn->query($sql);
$users = [];
while ($row = $result->fetch_assoc() ){
$users[] = new User($row);
}
// this array now contains all your users as User objects
var_dump($users);
// echo all user's details
foreach($users as $user) {
echo $user->getId();
echo ' - ';
echo $user->getName();
echo "\r\n";
}
Load a single user
$sql = 'SELECT * FROM user WHERE id = 1';
$result = $conn->query($sql);
if ($row = $result->fetch_assoc()) {
$user = new User($row);
} else {
exit('User ID does not exist');
}
// echo the user's ID and name
echo $user->getId();
echo ' - ';
echo $user->getName();
Resourses
Laracasts - https://laracasts.com/series/object-oriented-bootcamp-in-php
Search PHP OOP explained - https://www.google.co.uk/search?q=php+oop+explained
<?php
class user {
// Get users ID
function get_user_id() {
global $conn;
$data = array();
$sql = 'SELECT id FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row['id'] . ', ';
}
}
return $data;
}
// Get users name
function get_user_name() {
global $conn;
$data = array();
$sql = 'SELECT name FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row['name'] . ', ';
}
}
return $data;
}
}
$userId = new user;
$userName = new user;
// all user ids
$all_ids = $userId->get_user_id();
echo '<pre>';
print_r($all_ids);
// all user name
$all_name = $userId->get_user_name();
echo '<pre>';
print_r($all_name);`enter code here`
Check first response from both function after use if condition
You are comparing object with 1 not the value returned by function get_user_id().
So instead of
<?php $userId->get_user_id(); ?>
<?php $userName->get_user_name(); ?>
Try
<?php $id=$userId->get_user_id(); ?>
<?php $name= $userName->get_user_name(); ?>
and then put in your condition
if($id > 1){
echo $name;
} else {
echo 'not working';
}
I will suggest you to replace echo with return statement.
call your class as an object
$userid = user();
$username = user();
you can also try something like this
class user
{
// Get users ID
function get_user_id($id = "")
{
global $conn;
// check if id is empty or not
if(!empty($id)) {
$sql = 'SELECT id FROM users WHERE id = '.$id;
}else{
$sql = 'SELECT id FROM users';
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['id'] . ', '; }
}
}
// Get users name
function get_user_name($name = "")
{
global $conn;
// check if name is empty or not
if(!empty($name)) {
$sql = 'SELECT name FROM user WHERE name = '.$name;
}else{
$sql = 'SELECT name FROM user';
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['name'] . ', '; }
}
}
}
$userId = new user();
$userName = new user();
$userId->get_user_id(1);
$userName->get_user_name();
echo $userId;
echo $userName;
please make sure you sanitize the id and name before use
IN both get_user_id, get_user_name methods please
return $row = $result->fetch_assoc();
so, it will value comes in $userId, $userName and you can access it.
right now you return nothing so $user_id has null value so, it always goes in else condition.
Example
function get_user_id()
{
global $conn;
$sql = 'SELECT id FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$value = '';
while ($row = $result->fetch_assoc() ){
$value .= $row['id'] . ', ';
}
return $value;
}
}

Update statement in mysql not working although it is correct?

$sql = "UPDATE reservations SET status = '$this->status',remaining_time ='$this->remain',cost = '$this->cost' WHERE id = '$this->id'";
This code is not working although it's correct
I am using object oriented php.
$this->id is a variable passed by link from another page.
When I run the code it tells me it was successful but that there are zero affected rows.
The one line above is part of the following code:
<?php
class edit {
private $status;
private $remain;
private $cost;
private $id;
public function edit_data() {
$this->status = strtoupper(strip_tags($_POST['status']));
$this->remain = strip_tags($_POST['remain']);
$this->cost = strip_tags($_POST['cost']);
$submit = $_POST['submit'];
$this->id = $_GET['edit'];
$con = mysql_connect("localhost","root","")
or die("Failed to connect to the server: " . mysql_error());
mysql_select_db("Users")
or die("Failed to connect to the database: " . mysql_error());
if($submit) {
if($this->status and $this->remain and $this->cost) {
$sql = "UPDATE reservations SET status = '".$this->status."',remaining_time ='".$this->remain."',cost = '".$this->cost."' WHERE id = '".$this->id."'";
$query = mysql_query($sql,$con);
if(!$query) {
echo("Could not update data: " . mysql_error());
}
echo "<h4>Customer reservation data has been updated successfully.</h4>";
echo "Number of affected rows: " . mysql_affected_rows();
}
else {
echo "Please fill in all fields.";
}
}
mysql_close($con);
}
}
$edit = new edit();
echo $edit->edit_data();
?>
Are you sure about your concatenation?
$sql = "UPDATE reservations SET status = '$this->status',remaining_time ='$this->remain',cost = '$this->cost' WHERE id = '$this->id'";
Print $sql to see the value.
If your database is already updated, you will receive 0 affected lines.
I am not totally sure but try this,
"UPDATE reservations SET status = '".$this->status."',remaining_time ='".$this->remain."',cost = '".$this->cost."' WHERE id = '".$this->id."'";
It seems that your table doesn't contain a value which satisfies where condition.
You can check this by executing a simple query.
$sql = "select * from reservations where id='$this->id'";

PDO CRU are not functioning

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.

Error when I passed on values on function

Sorry about the last post I had. Here's my revision, please help me.
<?php
//connect database
$sql = "SELECT * FROM user where user_id = 8320 AND password = 'admin' ";
$query = pg_query($sql);
var_dump($row = pg_fetch_array($query)); //dumps correctly.
?>
BUT THE PROBLEM IS THIS..when I try to make it as a function LIKE:
function check($user_id, $password)
{
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($sql);
$row = pg_fetch_array($query);
return $row;
}
AND CALL IT HERE:
var_dump($data = check(8320, 'admin')); DUMPS NULL;
How come it ended up like this?
Its returning NULL because there is an error with your SQL query, and no results are being returned. You should do some error checking in your function, try this version:
function check($user_id, $password)
{
$dbconn = pg_connect("host=localhost dbname=test");
$sql = "SELECT * FROM user where user_id = $1 AND password = $2 ";
$result = pg_query_params($dbconn, $sql, array($user_id,$password));
$row = pg_fetch_array($result);
if (!$row) {
echo pg_last_error($dbconn);
} else {
return $row;
}
}
Try the code below. It should work fine for you.
$data = check(8320, 'admin');
var_dump($data);
Seems like your PostgreSQL resource is missing inside the function. You have two options.
Declare the connection resource inside the function using global.
Establish the connection inside the function.
This is the first option:
$conn = pg_connect('host','user','pass','db');
function check($user_id, $password)
{
global $conn;
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
And this is the second option:
function check($user_id, $password)
{
$conn = pg_connect('host','user','pass','db');
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
According to the PHP manual, You may omit connection resource, but it is not recommended, since it can be the cause of hard to find bugs in scripts.

Categories