How do I update the values in the table using PHP [closed] - php

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
How do i actually update the values of table using PHP ? This code is not showing any error and its not updating either.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error())
{
die("couldn't connect" . $conn->connect_error());
}
echo ("connected successfully");
$id = $_POST['Id'];
$name = $_POST['Name'];
$dept = $_POST['Department'];
$update = "update info set Name='$name', Department='$dept' where Id='$id'";
if($conn->query(update) === TRUE) {
echo ("Data updated successfully");
}
else
{
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
?>

Hope this one help you!
$update = "update info set Name='".$name."', Department='".$dept."' where Id='".$id."'";

Check this part of your code:
if($conn->query(update) === TRUE) {
where it should be:
if($conn->query($update) === TRUE) {
Make sure that you are using the correct credentials (host, username, password, database name) according to your MySQL database.
Also your table name and column name should be correct which are being used in your query.
Make sure that there is a match with your condition part of your query (... WHERE Id='$id'). Check it by running a query in your PhpMyAdmin page, or Search the ID, which is also the one you try to input in your form.
Make sure that the name of the passed variables ($_POST[]) are correct.
Be case sensitive.
Try changing your connection into:
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Other way to execute your query is to simply:
mysqli_query($conn,$update);
Recommendation:
You should escape the values of your variables before using them into your query by using mysqli_real_escape_string() function:
$name = mysqli_real_escape_string($conn,$_POST["Name"]);
Or better, so you won't need to worry about binding variables into your query and as well prevent SQL injections, you should move to mysqli_* prepared statement:
if($stmt = $conn->prepare("UPDATE info SET Name=?, Department=? WHERE Id=?")){
$stmt->bind_param("ssi",$_POST['Name'],$_POST['Department'],$_POST['Id']);
$stmt->execute();
$stmt->close();
}

$update = "update info set Name='".$name."', Department='".$dept."' where Id='".$id."'";
mysql_query($update);

$update = "update info set Name='".$name."',set Department='".$dept."' where Id='".$id."'";
if this is not help please provide form code.

Try this
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(!$conn)
{
die("ERROR CONNECTING TO DATABASE!");
}
echo "Connected Successfully";
$id = $_POST['Id'];
$name = $_POST['Name'];
$dept = $_POST['Department'];
$update = "update info set Name='$name', Department='$dept' where Id='$id'";
$qry = mysqli_query($conn,$update);
if(!$qry) {
echo "Error Updating Details".mysqli_error($conn);
}
else
{
echo "Data updated successfully";
}
mysqli_close($conn);
?>
(Optional) Use secure things. Change to this for more secure.
$id = mysqli_real_escape_string($conn,$_POST['Id']);
$name = mysqli_real_escape_string($conn,$_POST['Name']);
$dept = mysqli_real_escape_string($conn,$_POST['Department']);

Related

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.

Can't update arduino value to xampp database from link

I got the tutorial from this link
https://icreateproject.info/2014/12/14/arduino-save-data-to-database/
The tutorial is about how to save data from Arduino to xampp database over the local network.
I follow everything until step 3. This is the PHP code:
<?php
// Prepare variables for database connection
$dbusername = "arduino"; // enter database username, I used "arduino" in step 2.2
$dbpassword = "arduinotest"; // enter database password, I used "arduinotest" in step 2.2
$server = "localhost"; // IMPORTANT: if you are using XAMPP enter "localhost", but if you have an online website enter its address, ie."www.yourwebsite.com"
// Connect to your database
$dbconnect = mysql_pconnect($server, $dbusername, $dbpassword);
$dbselect = mysql_select_db("test",$dbconnect);
// Prepare the SQL statement
$sql = "INSERT INTO test.sensor (value) VALUES ('".$_GET["value"]."')";
// Execute SQL statement
mysql_query($sql);
?>
I tried to run this command in the link as mentioned in the tutorial
http://localhost/write_data.php?value=100
This is the error I get
Fatal error: Uncaught Error: Call to undefined function mysql_pconnect() in C:\xampp\htdocs\write_data.php:11 Stack trace: #0 {main} thrown in C:\xampp\htdocs\write_data.php on line 11
The mysql library that you are using is deprecated in php5.5
http://php.net/manual/en/function.mysql-connect.php
Here's an updated version with mysqli_connect
$dbusername = "arduino";
$dbpassword = "arduinotest";
$server = "localhost";
$database = 'test';
$mysqli = mysqli_connect($server, $dbusername, $dbpassword,$database);
// please validate the $_GET['value']
$sql = "INSERT INTO test.sensor (value) VALUES ('".$_GET["value"]."')";
mysqli_query($mysqli, $sql);
new mysqli http://php.net/manual/en/function.mysqli-connect.php
Somehow i managed to connect and changed the value by typing and auto insert using this code
<?php
header("Refresh:5");
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else {
echo "hello";
}
$value = $_GET['value'];
$sql = "INSERT INTO test.sensor (value) VALUES ($value)";
$sql = "INSERT INTO test.sensor (value)
VALUES ('255')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
And without this code, which is on line 28, i will get error so i have to put this code as well
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Thank you everyone for helping really appreciate it.

Checking already existing username or not MySQL, PHP

I Cannot Check whether the username already exist in database. I gone through existing questions that were answered here. None of them solved my problem. When i executes, it displays "Cannot select username from table", which i given inside die block. Code Is given below.
<?php
$username = $_POST['user_name'];
$password = $_POST['pass_word'];
$host = "localhost";
$db_username = "root";
$db_password = "";
$db_name = "my_db";
//create connection
$conn = #new mysqli($host, $db_username, $db_password, $db_name);
if (isset($_POST["submit"]))
{
# code...
//check connection established or not
if ($conn->connect_error)
{
die("Not Connected to DB");
}
else
{
$query = "SELECT 'usernamedb' FROM 'registration' WHERE usernamedb='$username'";
$result = mysqli_query($conn, $query) or die('Cannot select username from table');
if (mysqli_num_rows($result)>0)
{
$msg.="This username already exist. try Another !!";
}
else
{
$insert = "INSERT INTO 'registration'('id', 'usernamedb', 'password') VALUES ([$username],[$password])";
$insert_result = mysqli_query($conn,$insert) or die('INSERTION ERROR');
}
}
$conn->close();
}
?>
Hope someone will answer me.
First of all you should not use those unescaped queries.
But regarding your question you have an SQL error on your queries. You quoted table name. "FROM 'registration'" should be "FROM registration".

php delete record using id

This program is meant to delete a record when given the id.
php:
if ($_GET['type']=="file"){
$servername = "localhost";
$username = "****";
$password = "****";
$dbname = "****";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_error($conn)) {
die("Connection failed: " . mysqli_connect_error($conn));
}
$sql = "SELECT id,user, FROM CreationsAndFiles WHERE id =".$_GET['id']." LIMIT 1";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($result);
if ($row['user'] == $login_session){
$sql = "DELETE FROM CreationsAndFiles WHERE id=".$_GET['id'];
if(mysqli_query($conn, $sql)){echo "deleted";}
}
mysqli_close($conn);
//header("location: index.php?page=CreationsAndFiles");
}
the header is type=file&id=9
there is a record where id=9
It for no apparent reason will not work.
Your SQL syntax is wrong;
SELECT id,user, FROM CreationsAndFiles...
^ extra comma
should be simply
SELECT id,user FROM CreationsAndFiles...
You may want to sanitize your input though, for example simply entering type=file&id=id will most likely do bad things.

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