how to perform value calculation in mysql database using php - php

i have a column inside my user table named pairCount which has a value of 2 by default, but whenever an action occur, i want the value to be minus by one (1). so i wrote the following code
<?php
session_start();
require_once './include/Constants.php';
require_once './include/DatabaseConn.php';
require_once './vendor/autoload.php';
require_once './include/User.php';
require_once './include/Level.php';
use \phputil\JSON;
$user = User::getCurrentUser();
$db = new DatabaseConn();
$link = $db->connect();
$sql = "update users set `payee-1` = NULL, status = ?,`pairCount` = ? WHERE `payee-1` = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param('sss', $status, $pairCount, $payee1);
$status = PAIR;
//here is were i did the calculation, but it given me error
$pairCount = $pairCount (-1);
$payee1 = ($user->getUserName());
$res = $stmt->execute();
$stmt->store_result();
if ($res) {
echo "<h1>Congrate you have successfully unsubscribe to a pay this person";
header('Refresh: 3;url=icant3.php');
} else {
echo 'undone';
}

It is also possible to do that in your SQL query.
update users set `payee-1` = NULL, status = ?, `pairCount` = pairCount - 1 WHERE `payee-1` = ?
Then you don't need to do anything with $pairCount variable in your PHP code.

Related

How to count your user userID to count/select a row in a table?

I'm making a function that i have to check if a userid is in this table already: if not he has to get into another page yet. But for some reason I get "NULL" back instead of the number of the userID.
my class:
public function countHobbies($userID){
try{
$conn = Db::getConnection();
$statement = $conn->prepare("select * from hobby where userID = '".$userID."'");
$userID = $this->getUserID();
$statement->execute();
$aantal = $statement->fetchAll(PDO::FETCH_ASSOC); //
$aantal->execute();
}
catch(throwable $e){
$error = "Something went wrong";
}
}
and this is on my html page:
$userArray = $_SESSION['user_id'];
$userID = implode(" ", $userArray);
$hobby = new Hobby();
$count = $hobby->countHobbies($userID);
if($count == false){
echo "no";
//header('Location: hobby.php');
}
else{
echo "yes";
}
There are at least two things you need to fix:
Always use parameter binding on the SQL statement. It may not be a security problem in this particular instance, but do get into the habit of using prepared statements. Because otherwise you'll find yourself in situations where you should've but didn't. https://www.php.net/manual/en/security.database.sql-injection.php
The $userID variable must be assigned before it is used.
In the end, it could look like this:
$userID = $this->getUserID();
$statement = $conn->prepare("select * from hobby where userID = ?");
$statement->bind_param("s", $userID);

how to update empty value with bind parameters in php mysqli

I am creating message delete script in PHP MYSQLI. I have added zero value to update column. my script is working but I want to add zero value with bind parameters.
Here is my source code
<?php
require_once "config.php";
if (isset($_GET['to_id'])) {
$id = $_GET['to_id'];
$session_id = $_SESSION['userid'];
}
$stmt = $con->prepare("UPDATE pm SET from_delete = '0' WHERE id = ? AND from_id = ?");
$stmt->bind_param("ss", $id, $session_id);
if ($stmt->execute()) {
echo"deleted successfully";
} else {
echo "Failed to delete<br/>";
}
?>
Just add another placeholder ? and bind value to it:
$stmt = $con->prepare("UPDATE pm SET from_delete = ? WHERE id = ? AND from_id = ?");
$zero = '0';
$stmt->bind_param("sss", $zero, $id, $session_id);

Cannot Create Database PHP

I am beginning to create my own Interface to use with MySql though I cannot seem to create a database with the code I have at the bottom. Everything else works also i can echo out the $ObtainDatabase variable to see that it does have a value stored. Any suggestions would be great.
<?php
session_start();
//define connection
$conn = new mysqli('localhost', 'over_watch','XXXXXXx','billing');
//Variables
$UserEmail = $_SESSION['email'];
$MysqlUserDataBaseCreate = $_POST['create_database'];
//CheckIfUserExists
$SeeIfUserExist = $conn->prepare("SELECT (email) FROM database_users WHERE email= ?;");
$SeeIfUserExist->bind_param('s',$UserEmail);
$SeeIfUserExist->execute();
$SeeIfUserExist->bind_result($ObtainedEmail);
$SeeIfUserExist->store_result();
$SeeIfUserExist->fetch();
$RowsReturnedFromPreparedStatment = $SeeIfUserExist->num_rows();
if($RowsReturnedFromPreparedStatment < 1){
$InsertIntoDatabase = $conn->prepare("INSERT INTO database_users(email,check_if_created) VALUES(?,?);");
$InsertIntoDatabase->bind_param('ss',$UserEmail,$MysqlUserDataBaseCreate);
$InsertIntoDatabase->execute();
$SelectDatabaseToCreate = $conn->prepare(" SELECT (check_if_created) FROM database_users WHERE email = ?;");
$SelectDatabaseToCreate->bind_param('s', $UserEmail);
$SelectDatabaseToCreate->execute();
$SelectDatabaseToCreate->bind_result($ObtainDatabase);
$SelectDatabaseToCreate->fetch();
$CreateDatabase = "CREATE DATABASE $ObtainDatabase ;";
$conn->query($CreateDatabase);
}else{
echo 'user permitted to one database';
}
?>
Can you try this Code.
Details about this error can be found in the mysql docs. Reading those details makes it clear that the result sets of a prepared statement execution need to be fetched completely before executing another prepared statement on the same connection.
Here is the doc where you can refer
<?php
session_start();
//define connection
$conn = new mysqli('localhost', 'over_watch','XXXXXXx','billing');
//Variables
$UserEmail = $_SESSION['email'];
$MysqlUserDataBaseCreate = $_POST['create_database'];
//CheckIfUserExists
$SeeIfUserExist = $conn->prepare("SELECT (email) FROM database_users WHERE email= ?;");
$SeeIfUserExist->bind_param('s',$UserEmail);
$SeeIfUserExist->execute();
$SeeIfUserExist->store_result();
$SeeIfUserExist->bind_result($ObtainedEmail);
$SeeIfUserExist->store_result();
$SeeIfUserExist->fetch();
$RowsReturnedFromPreparedStatment = $SeeIfUserExist->num_rows();
if($RowsReturnedFromPreparedStatment < 1){
$InsertIntoDatabase = $conn->prepare("INSERT INTO database_users(email,check_if_created) VALUES(?,?);");
$InsertIntoDatabase->bind_param('ss',$UserEmail,$MysqlUserDataBaseCreate);
$InsertIntoDatabase->execute();
$InsertIntoDatabase->store_result();
$SelectDatabaseToCreate = $conn->prepare(" SELECT (check_if_created) FROM database_users WHERE email = ?;");
$SelectDatabaseToCreate->bind_param('s', $UserEmail);
$SelectDatabaseToCreate->execute();
$SelectDatabaseToCreate->store_result();
$SelectDatabaseToCreate->bind_result($ObtainDatabase);
$SelectDatabaseToCreate->fetch();
$CreateDatabase = "CREATE DATABASE $ObtainDatabase ;";
$conn->query($CreateDatabase);
}else{
echo 'user permitted to one database';
}
?>

Updating database using dropdown without using a submit button

I'm trying to update the table status value whenever I make a selection from the dropdown list.
The problem is I'm having a syntax error on my update query. I've read stuff about syntax error and I can't quite understand it. I think I'm gonna need a more specific help. Here's what I've done:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$databasename = "companydb";
try
{
$conn = new PDO("mysql:host=$hostname;dbname=$databasename",$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["status"]))
{
$query = "UPDATE tickets SET status = '$status' WHERE id = $id";
$statement = $conn->prepare($query);
$statement->execute(array('status' => $_POST["status"]));
$count = $statement->rowCount();
if($count > 0)
{
echo "Data Inserted Successfully..!";
}
else
{
echo "Data Insertion Failed";
}
}
else
{
echo "unknown index: 'status'";
}
}
catch(PDOException $error)
{
echo $error->getMessage();
}
?>
And here's my table schema:
You are not performing prepared statements properly. You need to add the placeholder in the query and not the variables. The variables should be added in the execute() line.
$query = "UPDATE tickets SET `status` = :status WHERE `id` = :id";
$statement = $conn->prepare($query);
$statement->execute(array(':status' => $_POST["status"],':id' => $id));
Also FYI, $id is undefined.
Try Changing this:
$query = "UPDATE tickets SET status = $status WHERE id = $id";

Php webservice looping

I am about to lose my mind.I dont have any php experince and I am struggling about php web service.
Here is my code;
<?php
private $username2 = "";
private $password2 = "";
private $DB_CONNECTION;
private $servername = "localhost";
private $username = "root";
private $password = "";
private $dbname = "dptest";
function __construct()
{
$this->DB_CONNECTION = mysqli_connect($this->servername, $this->username,
$this->password, $this->dbname);
}
function getUserType(){
$sql = "SELECT usertype FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
$result = mysqli_query($this->DB_CONNECTION,$sql);
//$value = mysqli_fetch_array($result);
while(!is_null($value = mysqli_fetch_array($result))){
return $value['usertype'];
}
}
}
This is my function code.The other is my login code;
<?php
include_once 'Authentication.php';
use user\Authentication;
$auth = new Authentication();
$auth->prepare($_POST);
$userStatus = $auth->isUserValidToLogIn();
if ($userStatus) {
// user existed
// So log him to main page
$json['success'] = 1;
$json['message'] = 'access granted';
$json['usertype'] = $auth->getUserType();
echo json_encode($json);
} else {
$json['success'] = 0;
$json['message'] = 'error!';
echo json_encode($json);
}
I am trying to get the user's type but when try to get the data form phpmyadmin local database it only gives the first column's usertype.When I try to get 2nd,3rd,4th so on.. user's usertype it doesnt return anything and blank page shows up on postman app.
Also my database looks like this;
usertype username password
admin despro 1234
client test 1234
client despro2 1234
client despro3 1234
The reason you are only getting one column back is because you only request the one column. In order to get the columns you want you need to explicitly request them in your query or use '*' in order to get all columns back. So your query should look like this in order to get all columns from the data table:
$sql = "SELECT * FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
In general, I highly recommend that you stop using MySQLi extension and start using PHP Data Objects (PDO). It makes it easy to use prepared statements. Which also makes your code safer.
Then your query could look something like this (this is NOT the complete code):
// connecting to db
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT *
FROM login_test
WHERE userName = :username
AND pass = :password;';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $username2, PDO::PARAM_STR);
$stmt->bindParam(':password', $password2, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
$response["userdata"] = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
}
Note that the code above is for returning multiple rows of data. If you just want the one row then use something like this:
if ($res) {
$response["userdata"] = array();
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
removing the 'while' statement.
You might want to take a look at this answer I gave, recently. It is a comprehensive example of using a webservice from an Android app.
How to insert all the SQL table data into an array in java [android studio]

Categories