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'");
}
}
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.
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;
}
}
I have this code which bring a single post from my database depend on id
global $connect;
$id = $_GET['id'];
$sql_query="SELECT * FROM `topics` WHERE id = {$id}";
$result = mysqli_query($connect,$sql_query);
while ($row = mysqli_fetch_assoc($result)) { ....}
How can i make this as function (My try) :
Function get_single_post($id) {
global $connect;
$id = (int)$id;
$sql_query="SELECT * FROM `topics` WHERE id = {$id}";
$result = mysqli_query($connect,$sql_query);
while ($row = mysqli_fetch_assoc($result)) {
$post[] = $row;
}
return $post;
}
to use this function i use this :
get_single_post($_GET['id']);
and when i call something i use :
$post['title']; for title as ex
Remember, a function returns a value, but that value must be assigned to a variable for you to be able to access it.
$post = get_single_post($_GET['id]);
Using the above should now allow you to access the post as you expect.
If your id is primary key than you don't need while loop as it will return only one result
modified function
Function get_single_post($id) {
global $connect;
$id = (int)$id;
$sql_query="SELECT * FROM `topics` WHERE id = {$id}";
$result = mysqli_query($connect,$sql_query);
return mysqli_fetch_assoc($result);
}
i have a login function in a seperate script(main.php) which is like the below
public function login($username,$password) {
$linkingcon = $this->getConnection();
$sqlquery = "SELECT ac.userID,ac.name,us.usertype FROM users us JOIN accounts ac ON us.userID = ac.userID WHERE us.username='$username' AND us.password='$password';";
$result = mysql_query($sqlquery , $linkingcon);
$this->throwMySQLExceptionOnError($linkingcon);
$row = mysql_fetch_array($result);
$survey = new stdClass();
if($row) {
$res->userID = (int)$row['userID'];
$res->name = $row['name'];
$res->usertype = (int)$row['usertype'];
$string = rand() . 'SurveyLand' . rand() . $username. $password;
$_SESSION['SURVEYLAND_KEY'] = md5($string);
} else {
$res = false;
}
return $res;
}
and im calling the above login function from another script but i am currently unable to call the "usertype" variable of the above function... below is the function that i have written to call the "usertype", can anybody check what is wrong with the below function
function login($parameters) {
$main = new Main();
$log = $main->login($parameters["username"], $parameters["password"]);
if($log != false){
$_SESSION['usertype'] = $res->usertype;
print_r($_SESSION);
}
return $log;
}
Try changing $res to $log in the second method. $res is the variable name you use in the first method, but is out of scope in the second method. However you assign the response of the first method (ie. $res) to $log in the second method.
function login($parameters) {
$main = new Main();
$log = $main->login($parameters["username"], $parameters["password"]);
if($log != false){
$_SESSION['usertype'] = $log->usertype;
print_r($_SESSION);
}
return $log;
}
I am trying to query my database and create values for later use in another function. My first function (get_users()) should query the requests database and find all users listed for the specific global_id - there will always be a maximum of 4 users for this query. Then I want to use a second function (get_results()) and insert the values that were retrieved from the first function (get_users()) into the second function. In other words, i need to put users1,2,3,4 into get_results($user1, $user2, $user3, $user4) in the second function.
Hoping someone can help! Here are my functions:
function get_users($global_id)
{
$result = mysql_query("SELECT user_purchased FROM requests WHERE global_id = '$global_id'");
$row = mysql_fetch_row($result);
$user1 = $row[0];
$user2 = $row[0];
$user3 = $row[0];
$user4 = $row[0];
}
function get_results($user1, $user2, $user3, $user4)
{
$result = mysql_query("SELECT * FROM results WHERE username != '$user1'
AND username != '$user2'
AND username != '$user3'
AND username != '$user4'
ORDER BY distance");
...more stuff to do here with the query
}
Thanks
Call the second function inside the first one:
function get_users($global_id)
{
$result = mysql_query("SELECT user_purchased FROM requests WHERE global_id = '$global_id'");
$count = 0;
while($row = mysql_fetch_array($result))
{
$user[$count] = $row;
$count++;
}
get_results($user[0],$user[1],$user[2],$user[3]);
}
function get_results($user1, $user2, $user3, $user4)
{
$result = mysql_query("SELECT * FROM results WHERE username != '$user1'
AND username != '$user2'
AND username != '$user3'
AND username != '$user4'
ORDER BY distance");
...more stuff to do here with the query
}
You can even simplify the get_results function to have one variable as an array instead of 4 varialbles
function get_results($users)
{
$result = mysql_query("SELECT * FROM results WHERE username != '".$users[0]."'
AND username != '".$users[1]."'
AND username != '".$users[2]."'
AND username != '".$users[3]."'
ORDER BY distance");
...more stuff to do here with the query
}
And you should call it like this in the first function
get_results($users);
Send the values as parameter to the another function.
function get_users($global_id)
{
$result = mysql_query("SELECT user_purchased FROM requests WHERE global_id = '$global_id'");
$row = mysql_fetch_row($result);
$user1 = $row[0];
$user2 = $row[0];
$user3 = $row[0];
$user4 = $row[0];
//now send
get_results($user1, $user2, $user3, $user4);
}