Update command of MySQL not working in PHP - php

This is my first very simple learning php program I have connected my PHP with MySQL Server and the Insert, Delete is working great but Update has some issue. When I press the update button nothing happens.
My database name is ddb3, the table name is student1.
The Apache server I am using is hosted via Xampp.
mysql_error(); shows no error and also no error in apache logfile
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("ddb3");
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$age = $_POST['age'];
mysql_query("INSERT INTO student1(name, age) VALUES ('$name', '$age');");
}
if(isset($_POST['delete'])) {
$name = $_POST['name'];
mysql_query("DELETE FROM student1 WHERE name = '$name';");
}
if(isset($_POST['update'])) {
$name = $_POST['name'];
$age = $_POST['age'];
mysql_query("UPDATE student1 SET name = '$name' WHERE age = '$age';");
}
?>
<html>
<body>
<center>
<form name='f1' action='prog3.php' method='post'>
<b>Name:<b><input type="text" name="name" size="20"><br>
<b>Age:<b><input type="text" name="age" size="5"><br>
<input type="submit" name="submit" value="Insert to Table"/>
<input type="submit" name="delete" value="Delete from Table"/>
<input type="submit" name="update" value="Update Row"/>
</form>
</center>
<?php
echo "<table align='center' name='t1' border='1' width=500px>
<tr><th>NAME</th><th>AGE</th></tr>";
$select = mysql_query("SELECT * FROM student1");
while($colmn = mysql_fetch_array($select)) {
echo "<tr><td>$colmn[0]</td><td>$colmn[1]</td></tr>";
}
echo "<table>";
?>
</body>
</html>

Describing the observed behavior as "not working" or "nothing happens" gives very little useful information, in determining what the actual problem is.
(How are you making the determination that "nothing happens", or that it's "not working"?)
I suggest adding some debugging output (for example, an echo or var_dump) at particular points in the code, to determine which path in the code is being taken. (Is $_POST['update'] set? Is the if condition evaluating to TRUE?)
https://ericlippert.com/2014/03/05/how-to-debug-small-programs/
I will note that it's very strange that we would change the name of a student based on age. For example, this statement will attempt to assign the same name to every student that is a particular age ...
UPDATE student1
SET name = 'Ted'
WHERE age = '19'
It would be very odd to do this. The SQL is valid. What is strange is which rows are being changed (all rows that have age=19), and the change that is being applied (changing the name of all the rows to the same value.)
It doesn't matter if the student's name is Jack, or Jill, or whatever. Every row in the table that has an age value of 19 is going to changed.
We typically don't store "age" as a column, but instead store a date of birth (dob). The DOB won't change. But age is going to change; age is the difference between DOB and the current (or some specified "as of") date. Age in years? Age in months, or days?
If we insist on storing age, then its much more likely that the age column is going to changed that the name column.
To identify which row should be updated... is name unique? Can there be two or more rows with the same name?
We probably want some unique identifier for the student, and use that in an UPDATE statment.
UPDATE student1 s
SET s.some_col = 'new_value'
WHERE s.id = 'unique_identifier'
Do not use the deprecated mysql_ interface for new development. Use PDO. (Or use mysqli_).
Also use prepared statements with bind placeholders to mitigate SQL Injection vulnerabilities. If for some unfathomable reason we can't do that, then at the very minimum, any potentially unsafe values incorporated into SQL text must be properly escaped.
Little Bobby Tables https://xkcd.com/327/
OWASP Project SQL Injection https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

Related

Eror in SQL syntax: Update query

I am a beginner to PHP and I am working on a profile page. The current problem is to change the name (This is a trial page that's why i am changing the name).For some reason i am getting the error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'lastName ='Lname' WHERE email ='qwerty#example.com'' at line 1.
<?php
include('server.php');
$db = mysqli_connect('localhost','root','','userdata');
$query = "SELECT * FROM data WHERE email = '".$_SESSION['username']."'";
$result = mysqli_query($db,$query);
$data = mysqli_fetch_assoc($result);
?>
<html>
<head>
<title>Profile</title>
</head>
<body>
<form method="POST" action="">
<p>First name: <input type="text" name="fname" value="<?php echo htmlspecialchars($data['firstName']); ?>" > </p>
<p>Last name: <input type="text" name="lname" value="<?php echo htmlspecialchars($data['lastName']); ?>"> </p>
<p><input type="Submit" name="confirm" value="Confirm"></p>
</form>
<?php
if(isset($_POST['confirm']))
{
$db = mysqli_connect('localhost','root','','userdata');
$query = "UPDATE data SET firstName ='".$_POST['fname']."' lastName ='".$_POST['lname']."' WHERE email ='".$_SESSION['username']."'";
mysqli_query($db,$query);
echo mysqli_error($db); //For checking error.Remove afterwords.
}
?>
<p>HOMEPAGE</p>
</body>
</html>
The server.php is a page where I manage the backend of the entire operation so it's not involved in this operation.The first PHP block takes data from the table. The HTML block creates a form where the user can edit the data. The PHP block should update data into the table.
I would appreciate any tips to further improve my page as i am still new to this.Thanks in advance
UPDATE:- Adding , to the query still does not change the situation.
you have an error in your sql statement (as the error message suggests). in mysql the error message usually points out the exact position where the error occurs, and it usually quotes the first character/word that causes the problem.
in your case, that's lastname. Your update query so far is:
UPDATE data SET firstName ='fname' lastName ='Lname' WHERE email ='qwerty#example.com'
-- ^ error occured here
when you look-up how UPDATE queries are supposed to look like (mysql docs) you'd find, that the different updated fields must be separated by comma:
UPDATE data SET firstName ='fname', lastName ='Lname' WHERE email ='qwerty#example.com'
-- ^ add this here
also, you're vulnerable to sql injections (please read up on them, and how to prevent them - this is done by prepared statements)
Please try with that(there was a missing comma on your SQL query).
$query = "UPDATE data SET firstName ='".$_POST['fname']."', lastName ='".$_POST['lname']."' WHERE email ='".$_SESSION['username']."'";
The other problem of using code that is open to sql injection is you can easily change the syntax of an sql statement from the input side. For example if for last name you input "O'connor", you change the syntax. Try to use echo $query and then analyse the output or better still,copy it and run it directly without using php
As mentioned in the comment. When updating multiple fields you need to comma separate them:
UPDATE data
set
field1="meh", /* <-- comma */
field2="foo"
where otherField="something"

Facing issue while running PHP script

I have a form in HTML which posts two values hostname and ip_address.
<form action="demo-select.php" method="post" />
<p>HOSTNAME/IPADDRESS: <input type="text" name="HOSTNAME" name="IP_ADDRESS" /></p>
<input type="submit" value="Submit" />
</form>
If I enter the hostname/ip_address and submit it, it will take me to demo-select.php script.
In demo-select.php script I'm able to get the output for hostname from my MySQL db. How should I get the output based on ip_address?
$value = $_POST['HOSTNAME'];
$query = "SELECT * FROM <tablename> WHERE HOSTNAME='$value'";
$result = mysql_query($query);
This script connects to a MySQL db and gets the output based on the hostname. What modifications should I make to get the output based on ip_address as well?
Table columns:
HOSTNAME
IP_ADDRESS
cpus
MEMORY
HTML:
You can't assign two names to an HTML element. I'd suggest that you either use two fields or use a dropdown / radio button along with the form field for the user to specify whether they're entering a hostname or an ip_address:
<form action="demo-select.php" method="post" />
<select name="address_type">
<option value="ip"> IP Address </option>
<option value="host"> Host Name </option>
</select>
<input type="text" name="host_name_or_address" />
<input type="submit" value="Submit" />
</form>
An assumption here is that you'd want the user to enter as input only one of hostname or ip_address in a single submit. If you want both to be relayed to the PHP at once, then please get rid of the select dropdown and use two input fields instead.
PHP:
Check what's been received in address_type and determine what query to use accordingly:
$address_type = $_POST['address_type'];
$value = $_POST['host_name_or_address'];
if($address_type == "host"){
// If looking for partial matches, use... WHERE HOSTNAME LIKE '%$value'
$sql = "SELECT * FROM <tablename> WHERE HOSTNAME = '$value' ";
}
else{
$sql = "SELECT * FROM <tablename> WHERE IP_ADDRESS = '$value' ";
}
Again, if you want both fields to be searched for at once, then along with the HTML edits indicated in the narration above, you'll have to receive in a PHP variable the value of the second input field too. Also then please get rid of the if-else construct here above and write a single, combined query as:
$sql = "SELECT * FROM <tablename> WHERE HOSTNAME = '$value1' AND IP_ADDRESS = '$value2' ";
Finally, please don't use mysql_*() functions in any PHP code. They're long deprecated and are very vulnerable to SQL Injection Attacks as Daniel has already suggested in his answer. Please have a look at MySQLi and PDO Prepared Statements instead. These utilities provide a cleaner way to write your queries and also a much safer mechanism to shield them against potential risks.

Specifying ID in Mysqli query in php

I'm working on a CMS site, I've got blog posts that I store in a database. I can create, edit and delete them. There's an issue though when I want to edit them.
I can't specify the WHERE clause in the update query to match the id of the blog post I'm trying to edit!
Suppose I've got a blog post with an id of '5'.
If I write this code for it, it works exactly the way it should.
$sqledit = "UPDATE paginas SET message='$_POST[message]' WHERE id= $_POST[id]";
But I don't want to edit just blog post #5, I want to edit the blog post that I'm updating. It seems to me this should work,
WHERE id= $_POST[id]";
... but it doesn't.
That just throws me an undefined id error. But it shouldn't because I can delete blog posts the exact same way with this particular code:
$sqldel = "DELETE FROM `paginas` WHERE id= $_POST[id]";
This does allow me to.
The code below is on the blog page, the edit query is in its own edit.php page
if (isset($_POST['edit'])) // if pressed, execute
{
echo
'<br><br> <div class="blogscript">
<form action="edit.php" method="post">Edit your stuff<br>
<input type="text" placeholder='. $pagetitle . ' ><br><br>
<textarea id="message2" name="message"><p>' . $message . '</p></textarea><br>
<input type="submit" name="editsubmit" value="Confirm" />
<input type="hidden" name="id" value="' . $id . '">. </form></div>';
}
I look forward to any tips I should try out.
EDIT:
This is my edit.php page
<?php
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "cmsbase";
$MySQLi_CON = new MySQLi($DB_host,$DB_user,$DB_pass,$DB_name);
if($MySQLi_CON->connect_errno)
{
die("ERROR : -> ".$MySQLi_CON->connect_error);
}
$sql = "UPDATE paginas SET message='$_POST[message]' WHERE id= $_POST[id]";
if ($MySQLi_CON->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $MySQLi_CON->error;
}
$MySQLi_CON->close(); //close connection
echo "<script>alert('Edited');location.href='index.php';</script>";
?>
EDIT: This is what the var_dump contains
In order for values to be present in $_POST, you need to have some element (e.g. <input>, <select>, <textarea>) inside your form with a name attribute set to the $_POST key you want.
You can add a hidden input to your form for id.
<input type='hidden' name='id' value='" . $id . "'>
Assuming you are getting the $message variable shown in that form code by selecting from your database, you should be able to get the id from there as well, or potentially from your $_GET if that is how you determine which post is being displayed.
(While this is not actually an answer, what I want to say does not fit in the comments)
Your line
$sql = "UPDATE paginas SET message='$_POST[message]' WHERE id= $_POST[id]";
Is horrific. This is the stuff of nightmares. Lets say that POSTed data in a form, is posted from a script from some robot somewhere, because I'm pretty sure you don't prevent XSRF in your code.
What if that script chose to post:
$_POST ==> array => message = "mwahahaha";
=> id = "1; DROP TABLE paginas;"
And you may think "how would they know my table name?" ,but that's easily found from other nefarious id inserts or other hacks on your code from other entry points which give a SELECT result, and many tables have common names such as "users" / "orders" / "baskets" / "touch-me" etc. (Ok well maybe not touch-me, but you get the idea).
Mysqli_real_escape_string() Could be used but thats only escaping quote marks and special characters, it does not mitigate SQL injection and compromise.
So, what should you do?
In this instance I want to draw your attention to PHP type juggling. Unlike many other languages, PHP has implied data types rather than specific data tyes, so a data type of "1.06" can be string and juggled to being a float as well.
Your id parameter in your MySQL is very probably a numeric integer value, so how can you be sure that the value of $_POST['id'] is also in integer rather than a SQL Instruction?
$id = (int)$_POST['id'];
This forces the value to be an integer, so
$id = (int)"1; DROP TABLE paginas;";
Is actually processed as $id = 1. Therefore saving you lots of compromised tables, spam rows and other nefarious rubbish all over your website, your database and your reputation.
Please take the following concept on board:
NEVER EVER TRUST ANY USER SUBMITTED CODE.
EVER

Incomplete data displayed from query

I am trying to make an update form using PHP, getting my data from MySQL 5. I have the fields set as a TINYTEXT type. My problem is when I attempt to display a field in my form for editing, the display stops at the first space. For example: my database my have "John Doe" in one field, but when I attempt to display that field I only see "John". Here is a portion of my code:
$id =mysql_real_escape_string ($_GET['id']);
if(isset($_POST['update'])) {
$UpdateQuery = "UPDATE members SET business_name='$_POST[business_name]', phone='$_POST[phone]', fax='$_POST[fax]', address1='$_POST[address1]', address2='$_POST[address2]', city='$_POST[city]', state='$_POST[state]', zip='$_POST[zip]', website='$_POST[website]', contact='$_POST[contact]', email='$_POST[email]', update_flag='$_POST[update_flag]', WHERE id='$id'";
mysql_query($UpdateQuery, $con);
}
$sql = "SELECT * FROM members WHERE id = $id";
$my_Data = mysql_query($sql,$con);
while($record = mysql_fetch_array($my_Data)) {
?>
<form action=listingupdate.php method=post>
<tr><input type=text name=business_name value=<?=$record['business_name']?> ></tr></br>
<tr><input type=text name=phone value=<?=$record['phone']?> > </tr></br>
<tr><input type=text name=fax value=<?=$record['fax']?> > </tr></br>
I have been googling several different ways, but I have not found what I am doing wrong. Would someone be so kind as to show my what I need to do to get all of the data in a field to display in my form?
Well a few things.. You should be using mysqli, not mysql since it is deprecated. Also you're calling mysql_real_escape_string on the id, but none of the other data so your script is wide open to SQL injection attacks. It looks like your code will fail if any of the posted data contains apostrophes. I'm not sure how you're planning to use GET and POST at the same time since your form, when submitted doesn't submit a GET value. With all that said, you should check the database to see if names are getting truncated in there, or if it's a client side issue.

php select to get a variable and then apply if else on it

I have a car rental system I am working on. When a user rents a car, the system should first check if the number of available cars is greater than 0, if yes, then make the adjustment "AVAILABLE = AVAILABLE+1" (in the MySQL table which keeps track of cars), which means, rent the car to the user. Also, I am trying to record which car went to which user. So I have another database table called rentalrecords which takes in the values of the Username of the logged in user, and ID of the car rented. Now, the problem is, my 'IF-ELSE' part is not executing as desired.
<div id="stylized" class="myform">
<form id="form" name="form" method="POST" action="renting.php" >
<h1>Rent a Car</h1>
<label>Car ID
<span class="small">eg. Enter 1 for Mer1</span>
</label>
<input type="text" name="ID" id="ID" />
<input type="submit" style="margin:30px 100px;" name="submit" value="Check-Out">
<div class="spacer"></div>
</form>
</div>
Now,the action of this form, which is renting.php, is as follows:
<?php
session_start();
if(!session_is_registered(theUSERNAME)){
header("location:customer_login.php");
}
mysql_CONNECT("xx", "xx", "xx") OR DIE("Unable to connect");
mysql_SELECT_DB("xx") OR DIE("Unable to select database");
$ID = $_POST['ID'];
$result = mysql_query("SELECT AVAILABLE FROM car WHERE ID='$ID'");
if(mysql_fetch_array($result)>0)
{
$query="UPDATE car SET AVAILABLE=AVAILABLE-1 WHERE ID='$ID'";
mysql_query($query);
$query = "insert into rentalrecords (USERNAME,ID,RENTED_ON) values ('$_SESSION[theUSERNAME]','$_POST[ID]',CURDATE())";
$result = mysql_query($query);
header("location: list_Clogged.php");
}
else
{
echo "<script>alert('The car you chose is currently unavailable!'); location.href='rent.php';</script>";
}
?>
Even though I have available=0, it still is NOT executing the else part and no matter what, it always executes the IF part. The ID and AVAILABLE are the attributes of my MySQL table called 'car' and the in rental records table i just want to insert these values. I am aware that the script is vulnerable to injection at the moment, but first I want to get things working! Any immediate help would be much appreciated.
You're trying to count a resource...
if(mysql_fetch_array($result)>0)
You need to obtain the results and then count an item within those results:
$res = mysql_fetch_assoc($result);
if($res[0]['AVAILABLE'] > 0)
Note $res[0] means first row of the results. You can also use mysql_fetch_row to obtain a single result.
Keep in mind, mysql_ functions shouldn't be used at all. Look into switching to mysqli or PDO.
Also, you need to sanitize input. You're just blindly accepting $_POST['ID']
The mysql_fetch_array function doesn't do what you think it does; it returns an array, not a single value.

Categories