unable to update table specific row - php

I had been trying many methods to update a specific row in my sql data base named juytdb having table users having colum names username and email. First I tried to connect and connection was successfull,
$localhost = "localhost";
$dbuser = "google";
$dbpass = "";
$dbname = "juytdb";
$connect = mysql_connect($localhost ,$dbuser ,$dbpass);
mysql_select_db($dbname, $connect);
Now while I wanted to update a specific row I used
session_start();
$username = $_SESSION['var']; //acutally users are logged so I just need to add their email
$email = $_POST['email']; //value I got from an inputbox
UPDATE users
SET email='google#gmail.com';
WHERE username='billy';
this does not work, I also tried
$sql = "UPDATE 'users' SET 'email' = '$email' WHERE 'username' = '$username'";
mysql_query($sql);
additionally the default values of email is set to "not added"

You have single quotes where you should have backquotes. Try this:
$sql = "UPDATE `users` SET `email` = '$email' WHERE `username` = '$username'";

Try this:
$sql = "UPDATE users SET email = '".$email."' WHERE username = ".$username;

Related

MySql/PHP data not getting removed

<?php
session_start();
//get the location name/address.
$address = $_POST['table'];
$_SESSION['myaddress'] = $address;
$username = $_SESSION['username'];
//connection details.
$sev_host = "localhost";
$sev_username = "root";
$sev_password = "";
$sev_db = "mydata";
//Connecting server with db.
$conn = mysqli_connect($sev_host, $sev_username, $sev_password, $sev_db);
if (!$conn) {
die("Error : " . mysqli_connect_error());
}
//Check if the table exist, and if not then create the table
$pre_check = "select location from users where username='$username";
$result_pre_check = mysqli_query($conn, $pre_check);
$pre_remove = "delete from $result_pre_check where username='$username'";
mysqli_query($conn, $pre_remove);
$pre_insert = "update users set location='$address' where username='$username'";
mysqli_query($conn, $pre_insert);
$sql = "CREATE TABLE $address (id int(6) unsigned auto_increment primary key, username varchar(255) not null, src varchar(255) not null)";
$sql2 = "INSERT INTO $address (id, username, src) VALUES ('', '$username', '')";
mysqli_query($conn, $sql);
mysqli_query($conn, $sql2);
?>
This is my php code, and I seem to have a problem in it. This code is attached to a button and runs when it is clicked, but it's not giving me the required result. As you can see that I am deleting a row on $pre_remove statement, but when the code runs everything works except that the required row is not removed from the table.
The code works fine and it doesn't give out any debug errors. Any ideas?
The reason this doesn't work lies within your query on $pre_remove
A good way to debug your code, would be to use functions like var_dump, print_r etc. to see what your variables actually contains.
In this specific case, the problem lies within delete from $result_pre_check
$result_pre_check is not a variable. Again, you can do a var_dump($result_pre_check) to see what this variable is / contains.
Your query to delete a user based on username would however work if it was:
$pre_remove = "delete from users where username='$username'";
You can try something like this,
$pre_remove = "DELETE FROM users WHERE username IN (
SELECT location FROM users WHERE username='$username'
)";
mysqli_query($conn, $pre_remove);
instead of ,
$pre_check = "select location from users where username='$username";
$result_pre_check = mysqli_query($conn, $pre_check);
$pre_remove = "delete from $result_pre_check where username='$username'";
mysqli_query($conn, $pre_remove);

Use PHP variable to search through SQL database

I have a database called $addressdb. I want to search through a table on that database with a result the user inputted ($usersName). My mistake is probably really stupid. I am new with mySQL.
<?php
//IF THE LOGIN is submitted...
if ($_POST['Login']){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "addressdb";
$usersName = $_POST['users'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT userID, userName FROM users WHERE userName =$usersName";
$result = mysqli_query($conn, $sql);
...
My line of error is
$sql = "SELECT userID, userName FROM users WHERE userName =$usersName";
More specifically the variable call.
Best approach is :
$sql = "SELECT userID, userName FROM users WHERE userName ='".mysqli_real_escape_string($conn, $usersName)."'";
Here it is not so applicable since you are passing the plain text. But when taking data from html page you should use this way.
Try something like this :
$sql = "SELECT userID, userName FROM users WHERE userName = '".$usersName."'";
You need to use quotes around your $userName.
$sql = "SELECT userID, userName FROM users WHERE userName = '$usersName'";
But to be clear, you should escape your user input at least with mysqli_real_escape_string($conn, $userName);

Converting To MYSQLI

I'm working to convert to MYSQLi. something i'm not entirely confident in just yet. I'm getting an error trying to breakdown this portion of my script.
<?php
// Parse the form data and add inventory item to the system
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$level = ($_POST['level']);
// See if that product name is an identical match to another product in the system
include "includes/db_conx.php";
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
$productMatch = mysqli_num_rows($sql); // count the output amount
if ($productMatch > 0) {
header("location: message.php?msg=usererror");
exit();
}
// Add this product into the database now
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['username']);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
$email = mysqli_real_escape_string($_POST['email']);
$p_hash = md5($password);
$sql = mysqli_query("INSERT INTO users (username, password, ip, email, level, date_added)
VALUES('$username','$p_hash','$ip','$email','$level',now())") or die (mysql_error());
header("location: order_complete.php");
exit();
}
?>
I believe I've got most of it down, but the second half of this is giving me fits. I'm trying to establish past
// Add this product into the database now
a mysqli conversion. I just can't seem to keep myself from mangling the script and throwing all kinds of errors. I believe I'm about half way there, but introducing select is throwing me off. Can someone help me to figure out this.
You are passing the $sql as a param to mysqli_num_rows() and it should be the result of a mysqli_query().
So change to this.
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
$productMatch = mysqli_num_rows($user_query); // count the output amount
A better name for that variable might be $user_result or something with the word result in.
Check the below mentioned code.
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$level = ($_POST['level']);
// See if that product name is an identical match to another product in the system
include "includes/db_conx.php"; // I guess it has $db_conx = mysqli_connect("localhost", "my_user", "my_password", "world");
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
$productMatch = mysqli_num_rows($user_query); // count the output amount
if ($productMatch > 0) {
header("location: message.php?msg=usererror");
exit();
}
// Add this product into the database now
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['username']);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
$email = mysqli_real_escape_string($db_conx, $_POST['email']);
$p_hash = md5($password);
$sql = mysqli_query($db_conx, "INSERT INTO users (username, password, ip, email, level, date_added) VALUES('$username','$p_hash','$ip','$email','$level',now())") or die (mysqli_error($db_conx));
header("location: order_complete.php");
exit();
}

can't perform SELECT query

My script is supposed to log the user into my database.
it does this by checking whether or not the username and password matches a row on the staff table.
if it is discovered that the username and password does exist it stores the username and password on the cookie.
The problem that I'm getting is that users are not being logged in.
It has been identified via the echo method that the following variables have the following values upon clicking the button
$row = 0
$username = whatever is in the username field on the form
this seems to indicate that there is something wrong with the query
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'the_shop';
mysql_select_db($dbname);
if(isset($_GET['submit']))
{
$username = $_GET['username'];
$password = md5($_GET['password']);
echo "$username + $password <br />";
// insert user into db
// $sql = "INSERT INTO `logindb`.`users` (`id`, `username`, `password`) VALUES (NULL, '".$username."', '".$password."');";
// echo $sql;
// $result = mysql_query($sql);
// getting user from db
$query = "SELECT Username, Password FROM staff WHERE `Username`='.$username.'";
$result = mysql_query($query)
or die(mysql_error());
$num=mysql_numrows($result);
echo $num;
if($num <= 0) {
echo "login not successful";
echo "$username";
}
else
{
$_SESSION['username'] = '$username';
$_SESSION['password'] = '$password';
//header("Location:Admin_Control_panel.php");
}
}
?>
For starters your $query has unwanted characters (.) in there.
"SELECT Username, Password FROM staff WHERE `Username`='.$username.'"
^ ^
Should be.
"SELECT Username, Password FROM staff WHERE `Username`= '$username'"
Without the dots.
This line:
$query = "SELECT Username, Password FROM staff WHERE `Username`='.$username.'";
Needs to be:
$query = "SELECT Username, Password FROM staff WHERE `Username`='$username'";
There is no need to concatenate the string since you're using double-quotes and PHP is parsing the $ values inside a double quoted string.
Your query should be:
$query = 'SELECT Username, Password FROM staff WHERE Username = ' . $username;
I suggest looking into PDO (PHP Data Objects) as an alternative to the method you are using and parameterising your variables.
http://php.net/manual/en/book.pdo.php
$query = "SELECT Username, Password FROM staff WHERE `Username`='$username'";

MySQL: how to subtract an update

i need to subtract an mysql update. here is the code:
<?php
session_start();
//=============Configuring Server and Database=======
$host = 'localhost';
$user = 'root';
$password = '';
//=============Data Base Information=================
$database = 'login';
$conn = mysql_connect($host,$user,$password) or die('Server Information is not Correct'); //Establish Connection with Server
mysql_select_db($database,$conn) or die('Database Information is not correct');
//===============End Server Configuration============
//=============Starting Registration Script==========
$username = mysql_real_escape_string($_POST['txtusername']);
//=============To Encrypt Password===================
//============New Variable of Password is Now with an Encrypted Value========
$insert = "UPDATE `users` SET `points` = (`points`-5) WHERE `username` = '".$username."'";
$insert = "UPDATE `users` SET `lodd` = (`lodd` +1) WHERE `username` = '".$username."'";
mysql_query($insert);
header('location: succes.php');
?>
the +1 work perfect but it dont work to -5... how can i do so that they get -5 points?
the +1 work correctly because the query with -5 will never be called as it is overwritten by the query that has +1.
you should have this code, (Although this is not the correct one)
$insert = "UPDATE `users` SET `points` = (`points`-5) WHERE `username` = '".$username."'";
mysql_query($insert);
// other codes
$insert = "UPDATE `users` SET `lodd` = (`lodd` +1) WHERE `username` = '".$username."'";
mysql_query($insert);
follow-up question: what are the dataypes of the two columns? are they unsigned or signed?
You're overwriting the first statement with the second. Try this:
$insert = "UPDATE `users` SET `points` = (`points`-5), `lodd` = (`lodd` +1) WHERE `username` = '".$username."'";
mysql_query($insert);

Categories