Update / echo dont work [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I don't understand why this doesn't work :
$sql = "UPDATE tbl_users SET balance = balance - 250 WHERE userID = <?php echo $row['userID']; ?>";
I work with PDO
What is wrong here? Need some help
session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in()) {
$user_home->redirect('index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$servername = "test.de.mysql";
$username = "test";
$password = "test";
$dbname = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE tbl_users SET balance = balance - 250 WHERE userID = <?php echo $row['userID']; ?>";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;

$sql = "UPDATE tbl_users SET balance = balance - 250 WHERE userID = " . intval($row['userID']);
Also i would mention you select all the userFields while you only need userID which is unnecessary mem waste.

Related

How to update (date) in PHP MySQL? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
Hello so basically I want to update a date in MySQL but to make the thing done in php form like:
<?php
$sql = "UPDATE users
set expire_date=CURRENT_DATE + INTERVAL 30 DAY
WHERE email='" . $_SESSION['user_email'] . "'";
?>
Sorry If I described my question weirdly but Its important for my project, any help appreciated!
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = " $sql = "UPDATE users
set expire_date=DATE_ADD(`date` , INTERVAL 30 DAY)
WHERE email='" . $_SESSION['user_email'] . "'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>

i want get data from table sql [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
i have a table register with email and username colums.
> ex - username email
> test test#gmail.com
> new new#gmail.com
SELECT * FROM Register WHERE email='test#gmail.com'
I can get this colom ,but i cant select username.i want assign username to variable
I think you want something like this if you use MySQL :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT username, email FROM MyTable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "username: " . $row["username"]. " - email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
In my opinion you're probably a beginner with web development with databases.
I recommend you w3chools. You can reed various examples in this site:
https://www.w3schools.com/php/php_mysql_select.asp
Your question is not clear, but if you are new with database I recommend you to start with PDO instead of mysqli.
<?php
//Db connection
function pdo_connect_mysql() {
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'phpcrud';
try {
return new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS);
} catch (PDOException $exception) {
// If there is an error with the connection, stop the script and display the error.
exit('Failed to connect to database!');
}
}
// User Input
$username = 'john';
$email = 'john#gmail.com';
$sql = 'SELECT * FROM register WHERE username = ? email = ?';
$stmt = pdo_connect_mysql() ->prepare($sql);
$stmt->execute([$username, $email]);
$register = $stmt->fetchAll();
?>

How to search for a specific column data using a variable and update its column data [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
What I'm trying to do: I'm trying to change a specific column under the 'username' row where the username is the same as $loginuser var and change the speedrunhighscore row in that column into a new speedruhighscore.
The problem:
in the code below there is a line in which I put in bold, and that's the line I'm trying to run to change the data in my database but nothing changes in my database but the echos are all running smoothly.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "smolgames";
$speedrunhighscore = $_POST["speedrunhighscore"];
$loginuser = $_POST["loginuser"];
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("connection failed: " . $conn->connect_error);
}
$sql = "SELECT username FROM userinfos WHERE username = '" . $loginuser . "'";
$result = $conn->query($sql);
if($result->num_rows > 0){
**$sql3 = "UPDATE userinfos SET speedrunhighscore = (' . $speedrunhighscore . ') WHERE username = '" . $loginuser . "'";**
echo "updating your new highscore":
if($conn->query($sql3) === TRUE){
echo "your highscore have been updated successfully!";
}
else{
echo "Error: ". $sql3 . "<br>" . $conn->error;
}
}
else{
echo "no usernames found";
if($conn->query($sql2) === TRUE){
echo "new highscore send successfully";
}
else{
echo "Error: ". $sql2 . "<br>" . $conn->error;
}
}
$conn->close();
?>
note: the variable loginuser changes from a string I post using unity C#
For starters, you should be using prepared statements with bounded placeholders. This ensures your query is not vulnerable to SQL injection attacks, and ensures that even usernames such as O'Riley would work.
Next up, you don't need to check if the row exists before updating it -- you can just attempt to perform the update right away, and check how many rows was in fact updated.
Lastly, you should be configuring your MySQLi connection to throw exceptions on error, this means that you don't have to do individual error handling for each and every query.
<?php
// Configure MySQLi to throw exceptions on failure instead
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "smolgames";
$speedrunhighscore = $_POST["speedrunhighscore"];
$loginuser = $_POST["loginuser"];
try {
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("UPDATE userinfos
SET speedrunhighscore = ?
WHERE username = ?");
$stmt->bind_param("ss", $speedrunhighscore, $loginuser);
$stmt->execute();
$affectedRows = $stmt->affected_rows;
$stmt->close();
if ($affectedRows) {
echo "your highscore have been updated successfully!";
} else {
echo "no usernames found";
}
} catch (Exception $e) {
// Handle the exception
// Log it, send a message to the user "something went wrong"
}
You should be implementing some sort of authentication and authorization layer, as now you can just submit someone else's username with any arbitrary highscore, and you can basically update any scores in the table.

Safe way to connect database with php using MySQLi [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I just cut down my long code to small so its easy to understand. I am building php based website. I am using MySQLi as i know some MySQL. And for me PDO is hard to learn in small time period.
I created three files
- db.con.php
- index.php
- logout.php
I will post my all three files and i just want to know if its safe or there is any Vulnerability
And i thanks to all who see my question and appreciate answer alot.
db.con.php
<?php
//db.con.php
class DB {
protected $db_name = 'demo';
protected $db_user = 'root';
protected $db_pass = '';
protected $db_host = 'localhost';
public function connect() {
$DBerror = 'Database Error';
$connection = ($GLOBALS["___mysqli_ston"] = mysqli_connect($this->db_host, $this->db_user, $this->db_pass)) or die($DBerror);
((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE $this->db_name")) or die($DBerror);
return true;
}
}
$db = new DB();
$db->connect();
//start session
session_start();
?>
index.php
<?php
require_once 'db.con.php';
$userID = $_GET['userID'];
$userID = mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $userID);
$CheckQuery = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM users WHERE id='$userID'");
$VerifyID = mysqli_num_rows($CheckQuery);
if ($VerifyID !== 1){
header("Location: logout.php");
}
while ($row = mysqli_fetch_assoc($CheckQuery)) {
$id = $row['id'];
$name = $row['name'];
}
echo "My id is $id and my name is $name";
?>
And last logout.php
<?php
//logout.php
session_start();
session_destroy();
echo "Logout successful";
?>
Make it PDO not mysqli
Leave DB class alone for a while
Learn prepared statements
db.con.php
<?php
$dsn = "mysql:host=localhost;dbname=demo;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, 'root', '', $opt);
session_start();
index.php
<?php
require_once 'db.con.php';
$stmt = $pdo->prepare("SELECT 1 FROM users WHERE id=?");
$stmt->execute(array($_GET['userID']));
$row = $stmt->fetch();
if(!$row) {
header("Location: logout.php");
exit;
}
$id = $row['id'];
$name = $row['name'];
echo "My id is $id and my name is $name";
Look it works better without homebrewed wrappers

PHP SQL - Inserting into a table [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a problem dear stackoverflowers, could someone please help me out?
This is my code:
<?php
$host = "localhost";
$user = "root";
$pass = "password";
$db = "hotelcalifornia";
$room_Number = ($_POST['Room_Number']);
$room_Category = ($_POST['Room_Category']);
$room_Description = ($_POST['Room_Description']);
$room_Detail = ($_POST['Room_Detail']);
$conn = mysql_connect($host, $user, $pass);
$db = mysql_select_db($db, $conn);
mysql_select_db($db, $conn);
$sql = "INSERT TO room (roomNumber, roomCategory, roomDescription,roomDetail) VALUES ('$room_Number','$room_Category', '$room_Description','$room_Detail')";
mysql_query($sql, $conn);
?>
Can someone tell me why i can't insert this data into my table in the database?
It's not INSERT TO, it's INSERT INTO.Thus you shouldn't use mysql functions, instead use mysqli functions as your code is vulnerable to SQL injection.
$host = "localhost";
$user = "root";
$pass = "password";
$db = "hotelcalifornia";
$conn = new mysqli($host, $user, $pass, $db);
$room_Number = $_POST['Room_Number'];
$room_Category = $_POST['Room_Category'];
$room_Description = $_POST['Room_Description'];
$room_Detail = $_POST['Room_Detail'];
$sql = "INSERT INTO room (roomNumber, roomCategory, roomDescription,roomDetail) VALUES (?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('iiss', $room_Number, $room_Category, $room_Description, $room_Detail);
if ($stmt->execute()) {
if($stmt->affected_rows > 0){
echo "New record created successfully";
}
} else {
echo "Error: " . $sql . "<br>" . $stmt->error;
}
$stmt->close();
Within the line $stmt->bind_param('iiss', $room_Number, $room_Category, $room_Description, $room_Detail); i corresponds to the integer where s corresponds to string by the order of the variables, which I assume $room_Number and $room_Category are integer values where $room_Description and $room_Detail are string values.

Categories