I want to update 2 of my database's fields according to user input.My code is something like this:
<body>
<?php
$db_server["host"] = "localhost"; //database server
$db_server["username"] = "root"; // DB username
$db_server["password"] = "mypass"; // DB password
$db_server["database"] = "mudb";// database name
$dbc = mysql_connect($db_server["host"], $db_server["username"], $db_server["password"]);
mysql_select_db($db_server["database"], $dbc);
$user = $_COOKIE['mycookie'];
$q = "SELECT * FROM members WHERE username='$user'";
$r = mysql_query( $q,$dbc);
while ($row = mysql_fetch_array($r, MYSQLI_ASSOC)) {
echo 'username: '.$row['username'], '<br/>';
$password=$row['password'];
?>
<form method="post" id="changepasswordform" >
<input type="password" id="newpassword" name="newpassword"/>
<input type="submit" name="changepasswordbutton" >
</form>
<?php
echo 'email: '.$row['email'], '<br/>';
}
?>
<form method="post" id="changeemailform" >
<input type="text" id="newemail" name="newemail"/>
<input type="submit" value="αλλαγή" name="changeemailbutton" >
</form>
<?php
}
if (isset($_POST['changepasswordbutton'])){
$newpassword=$_POST['newpassword'];
$q2 = "UPDATE members SET password=$newpassword WHERE username='$user'";
$r2 = mysql_query($q2,$dbc);
}
if (isset($_POST['changeemailbutton'])){
$newemail=$_POST['newemail'];
$q3 = "UPDATE members SET email=$newemail WHERE username='$user'";
$r3 = #mysql_query( $q3,$dbc);
}
?>
</body>
However although my connection to my db is ok(SELECT displays results as expected) when i try to UPDATE , the values inside my db remain the same.I checked the values of $newpassword and $newemail and they do contain the user inputs each time.What am i missing here?
You're missing the '' (quotes) that supposed to surround the password field.
change:
UPDATE members SET password=$newpassword WHERE username='$user'
to:
UPDATE members SET password='{mysql_real_escape_string($password)}'
WHERE username='{mysql_real_escape_string($user)}'
IMPORTANT:
And even though it's not related, please don't use mysql_* functions - it's deprecated and vulnerable to sql-injection. Better use PDO or MySQLi.
This will do the trick and is save for sql injection (mysql_real_escape_string):
$q2 = "UPDATE members SET
password='". mysql_real_escape_string($password) ."'
WHERE username='". mysql_real_escape_string($user) ."';
But off course you shouldn't use mysql_* anymore, I'm just giving an example for your specific case.
Related
This code is meant to check the submitted form values and update the table,
however it just replaces the field with a blank
Any ideas where it is gone wrong, please?
<form action = "update.php" method = "POST">
<p>
New Name: <input type "text" name="name">
<input type= "submit">
</p>
</form>
<?php
require ('/var/www/html/site1/connect_db.php');
if(!empty($_POST['name']) && !is_numeric($_POST['name']))
{
$name=$_POST['name'];
$name=mysqli_real_escape_string($dbc,$query);
$name=strip_tags($name);
#$query='update customers SET customerName = '".$name."' where customerNumber=114';
$query = "update customers ". "SET customerName = $name"."where customerNumber=114" ;
mysqli_query($dbc,$query);
}
else
{
echo $name;
}
$query = 'select * from customers where customerNumber=103';
$result = mysqli_query($dbc,$query);
while ($row=mysqli_fetch_array($result, MYSQLI_NUM))
{
echo"<p>Name : $row[1]</p>";
}
mysqli_close($dbc);
?>
You are updating customer number 114 but selecting 103 out, whose name may be blank.
Your update statement needs to have quotes around the $name bit as below:
$query = "UPDATE customers SET customerName = '$name' WHERE customerNumber=114";
Edit: please see the parameterised query advice in the question comments.
I have created a page where it lets users to edit their information which is stored in the database. However i can't get the WHERE clause to work it just keeps coming up with entry not found. Any help would be great thanks.!
<?php
mysql_connect('localhost', 'root', 'password') or die(mysql_error());
mysql_select_db("peopletank") or die(mysql_error());
$query = mysql_query("SELECT * FROM users WHERE id='$id'")
or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$id = $row['id'];
$firstname= $row['firstname'];
$secondname= $row['secondname'];
}
?>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?php echo $id;?>">
Value1: <input type="text" name="value1" value="<?php echo $firstname;?>">
<br>
Value2: <input type="text" name="value2" value="<?php echo $secondname?>">
<input type="Submit" value="Change">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
Try this :
$query = mysql_query("SELECT * FROM users WHERE id='".$id."'");
Make sure your $id is populated correctly. Try checking the value first if the query still didn't showed up like this :
echo 'The id is : '.$id;
$query = mysql_query("SELECT * FROM users WHERE id='".$id."'");
If the $id is populated correctly but still return no result then run the query manually in your mysql database, probably there is no result for specified $id
And while populating data, no need to fetch $id while you just have same $id ini this query.
while($row = mysql_fetch_array($query)) {
$id = $row['id']; /* << Remove this */
$firstname= $row['firstname'];
$secondname= $row['secondname'];
}
I aint 100% sure if its one of these things:
1) Try ending the statements with ;
2) Numbers dont have to be between ''
3) Try putting names of columns between ``
4) use LIMIT 1 where you can (makes things faster but not important)
5) Always try to use a selecter (faster)
<?
if ( $query = mysql_query("SELECT `firstname`,`secondname` FROM `users` WHERE (`id` = $id) LIMIT 1;"))
{
if ($r = mysql_fetch_assoc($query))
{
$firstname = $r['firstname'];
$secondname = $r['secondname'];
}
}
?>
My update script is not working.. I don't know what im missing..
but i can't update the table ... Went to w3school to know about the update in php but still it wont work...
-noob coder-
<?php
include 'Core/init.php';
protect_page();
include 'Includes/Overall/overallheader.php';
?>
<h1>Update School Year and Semester</h1>
<?php
$con=mysqli_connect("localhost","root","1234","database3");
// Check connection
$sy = $_POST['school_year'];
$sem = $_POST['semester'];
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ( isset($_POST['submit'] ) )
{
$sql = "UPDATE `activesys` SET `activeschoolyear` = '$sy' AND `activesemester` = '$sem'";
$exec = mysql_query($sql) or die(mysql_error());
}
?>
<form action="" method="post">
<ul>
<li>
School Year:<br />
<input type="text" name="school_year">
</li>
<li>
Semester:<br />
<input type="text" name="semester">
</li>
<li>
<input type="submit" value="submit">
</li>
</ul>
</form>
<?php
include 'Includes/Overall/overallfooter.php';
?>
Even though its not directly realated:
Please make sure to escape Request data that you load from $_POST or $_GET by using mysql_escape_string . Otherwise it would be easy to inject SQL in your query, which would allow to run harmfull sql in your system, like deleting the database or manipulating the data.
http://en.wikipedia.org/wiki/SQL_injection
You have missed where condition in update query .. try this
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
$sql = "UPDATE `activesys` SET `activeschoolyear` = '$sy' AND `activesemester` = '$sem'" WHERE some_column=some_value;
First, you mix mysqli and mysql. Second, mysql_query/mysqli_query have two parameters. Third, your sql is not right.
So, change your $exec = mysql_query($sql) or die(mysql_error())
to $exec = mysqli_query($con,$sql) or die(mysqli_error($con));
change your sql to :
$sql = "UPDATE `activesys` SET `activeschoolyear` = '$sy' , `activesemester` = '$sem'";
but you didn't have a where condition here, if in your table you have set an
anto-increment key and set it to primary key, you could add some condition end of you sql,otherwise it will
update all your records.
$sql = "UPDATE `activesys` SET `activeschoolyear` = '$sy' , `activesemester` = '$sem' where id={$id}"
$id is one recod from you table.
this should work for you excute an update..
Try using this :
1) use "action" attribute of the tag
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
2) check whether your form has beensubmitted :
if(isset($_POST['submit']))
3) Use WHERE condition in your sql query. You final query should look like this :
<?php
if(isset($_POST['submit']))
{
$con = mysqli_connect("localhost","root","1234","database3");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$query = "
UPDATE `activesys`
SET `activeschoolyear` = '$sy',`activesemester` = '$sem'
WHERE `columnName` = `columnValue`
";
mysqli_query($con,$query);
}
I can't seem to find a solution to this and i've looked for similar threads too but no luck
Basically here's my code, when you click Update it's meant to display your current name in the form fields then you can overwrite them and submit the changes, however sadly it will not update, it only displays the originally set first name and last name and does not update the database so therefore not displaying the new set names.
<?php
include('../connect_db.php');
$res = mysqli_query($dbconnection, "SELECT * FROM users");
$row = mysqli_fetch_array($res);
if(isset($_POST['newFirst']) && isset($_POST['newLast'])){
$newFirst = $_POST['newFirst'];
$newLast = $_POST['newLast'];
$id = $_POST['id'];
$sql = "UPDATE users SET first_name='$newFirst', last_name='$newLast' WHERE id='$id'";
$res = mysqli_query($dbconnection, $sql);
}
?>
<div id="editSection">
<h3>Edit Details</h3>
<form action="edit_profile.php" method="POST">
<input type="hidden" value="<?php echo $row[0];?>" name="id"/>
<h2>First Name</h2>
<input type="text" name="newFirst" value="<?php echo $row[1];?>">
<h2>Last Name</h2>
<input type="text" name="newLast" value="<?php echo $row[2];?>">
<input type="submit" value="Update">
</form>
</div>
Any help would be greatly appreciated :)
Kind Regards
~ Matt
You have to connect to DB before updating.so use
$con=mysqli_connect("localhost","my_user","my_password","my_db");
There are several other errors like you have to make $POST['newFirst'] as $_POST['newFirst'] like this
if(isset($_POST['newFirst']) && isset($_POST['newLast'])){
And change the query to
$sql = "UPDATE users SET first_name='$newFirst',last_name='$newLast' WHERE id= '$id'";
beacuse you have error at end of query id='first_name='$id' which is wrong
I see some error in the query
$sql = "UPDATE users SET first_name='$newFirst',
last_name='$newLast' WHERE id='first_name='$id'";
should be
$sql = "UPDATE users SET first_name='$newFirst',
last_name='$newLast' WHERE id= '$id'";
also
if(isset($POST['newFirst']) && isset($POST['newLast'])){
should be
if(isset($_POST['newFirst']) && isset($_POST['newLast'])){
You are using $POST wrong in your if-condition.
It must be called $_POST[..].
Also you should take a look at your WHERE in your update query.
I think you mean: WHERE id= '$id'
You should get your id from $_POST['id']; which is your row ID i suppose and also the update query must be where id=$id.
$id = $_POST['id'];
$sql = "UPDATE users SET first_name='$newFirst', last_name='$newLast' WHERE id=$id";
Also have you checked in DB after the update? the row[0], row[1], row[2] used will have old set of values used during select before the update happened. can you have the mysqli_fetch_array($res) after the update call?
Here is the page that is supposed to allow a logged in member to transfere an amount they choose to another user on the system i have been working on this for days and found little about it online that actually helps and only found a few snippets here and there that used prepared statements which failed when i edited it so i want to keep it all mysqli for now until i understand prepared statements better or i learn OOP Or PDO but for now i mainly wish to find out why this failes when it sais it works successfully and when i cant see any errors with this code also i have edited this many times so i have tryed various ways but i must be missing something i have also included the db_conx page as a line in this code and the other included line is just to do with checking if a user is logged in, any ideas what may be wrong with this as its not working.
<form name="username" method="post" action="index.php">
<input type="text" name="username" placeholder="Transfere To Username"/> <br />
<input type="text" name="amount" placeholder="Amount To Send" style="centered"/><br />
<input type="submit" value="continue"/>
</form>
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
session_start();
$username = $_SESSION['username'];
echo "<p><br>";
echo "Logged In As $username";
echo "<p><br>";
include_once("../../../php_includes/check_login_status.php");
require("db_conx.php");
if (isset($_POST["username"]) && !empty($_POST["amount"])) {
$username2 = preg_replace('#[^a-z0-9]#i', '', $_POST['username']);
$amount = preg_replace('#[^a-z0-9.]#i', '', $_POST['amount']);
$amount = (int)$amount;
$select_result = ("SELECT balance FROM users WHERE username = '$username' LIMIT 1") or die(mysqli_error($select_result));
$user_query = mysqli_query($db_conx, $select_result);
$numrows = mysqli_num_rows($user_query);
if ($numrows < 1) {
echo "Error Selecting Data Try Again Or Go Back";
}
while ($select = mysqli_fetch_array($select_result, MYSQLI_ASSOC)) {
$available_balance = $select["balance"];
}
if($available_balance>=$amount){
$result = ("UPDATE users SET balance = balance - '$amount' WHERE username = '$username' LIMIT 1") or die(mysqli_error($result));
$user_query2 = mysqli_query($db_conx, $result);
$numrows2 = mysqli_affected_rows();
if ($numrows2 < 1) {
echo "Error Updating Data Try Again Or Go Back";
}
$result2 = ("UPDATE users SET balance = balance + '$amount' WHERE username = '$username2' LIMIT 1") or die(mysqli_error($result2));
$user_query3 = mysqli_query($db_conx, $result2);
$numrows3 = mysqli_affected_rows();
if ($numrows3 < 1) {
echo "Error Updating Data Try Again Or Go Back";
}}
echo "Amount Of $amount Has Been Transferred To $username2";
} else {
echo "No Amount Has Been Set, Try Again Or Go Back";
}
?>
Don't put table names in single quotes. Single quotes are for string literals and date literals.
SELECT * FROM 'users' WHERE 'username' = $username -- WRONG
SELECT * FROM users WHERE username = '$username' -- BETTER, BUT INSECURE
SELECT * FROM users WHERE username = ? -- BEST
The same is true for your UPDATE statements. Don't quote table names or column names, but do quote strings.
For good examples of using prepared queries with parameters, the most popular and frequently-referenced post on StackOverflow about this is How can I prevent SQL injection in PHP?
Check the return value from mysqli_query(). It will be false if there's a problem. If it returns false, then check mysqli_error() to find out what the problem is. For example, putting a quoted string where a table name should be.
If you don't want to write code after each mysqli_query() to check the return value, you can just configure mysqli to throw an exception when an error occurs. Just do this once at the top of your PHP file, it'll remain in effect for the rest of the script.
mysqli_report(MYSQLI_REPORT_STRICT);
You should understand the difference between mysqli_num_rows() and mysqli_affected_rows(). mysqli_num_rows() counts the rows in the result set from a SELECT, and it only works after you have fetched the rows. Whereas mysqli_affected_rows() counts the rows changed by an INSERT, UPDATE, or DELETE.
Checking the result from mysqli_affected_rows(), you may find that your UPDATEs are changing zero rows. This happens either if the WHERE clause matches no rows (that is, there is no user for $username or $username2), or if the SET clause specifies values that result in no change to the column. You should make sure $amount is not 0.
Try this if you have not. Try to get meaningful errors from database results and requests.
$numrows = mysqli_num_rows($user_query) or die(mysql_error()) ;
$select = mysqli_fetch_array($select_result, MYSQLI_ASSOC) or die(mysql_error());
I rewrote this and got it working with the following, thanks for all your help (everyone who replied)
<form name="username" method="POST" action="index.php" autocomplete="off">
<input type="text" name="username" placeholder="Transfer To Username"/> <br />
<input type="text" name="amount" placeholder="Amount To Send" style="centered"/><br />
<input type="submit" value="continue"/>
</form>
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
session_start();
$username = $_SESSION['username'];
echo "<p><br>";
echo "Logged In As $username";
echo "<p><br>";
include_once("db_conx.php");
if (isset($_POST["username"]) && !empty($_POST["amount"])) {
$username2 = preg_replace('#[^a-z0-9]#i', '', $_POST['username']);
$amount = preg_replace('#[^a-z0-9.]#i', '', $_POST['amount']);
$amount = (int)$amount;
$sql = ("SELECT balance FROM users WHERE username = '$username' AND balance >= $amount");
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query) or die(mysql_error());
if ($numrows < 1) {
echo "<h3>Failed To Complete </h3>";
}
else {
echo "Amount Of $amount Has Been Transferred To $username2 You May Now Go Back";
$sql = ("UPDATE users SET balance = balance - '$amount' WHERE username = '$username' LIMIT 1");
$query = mysqli_query($db_conx, $sql);
$sql = ("UPDATE users SET balance = balance + '$amount' WHERE username = '$username2' LIMIT 1");
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query) or die(mysql_error());
if ($numrows < 1) {
echo "<h3>Failed To Complete Transfer! Try Again Or Go Back</h3>";
}
else {
echo "<h3>Failed To Complete Transfer! Try Again Or Go Back</h3> ";
}
}
}
?>
Back To Balance Page</h3>