I am new to PHP and working on small local webpage and database that takes user information and database stores the same user information .If i Login with ADMIN it shows all data. My requirement is that the loggined user is an admin, then he has a right to edit all the informtion of the users that i stored in the database.And this is to be done using GET method . How it will be working?
Heres some example code purely to demonstrate how to update a table using a GET method form. The code doesn't have any kind of error checking and assumes you already know how to connect to your database (and that its MySQL).
Assuming you've landed on a page which invites you to edit data, which record you're editing is referenced by an 'id' variable on the URL which matches a numerical primary key in your database table.
<?php
$SQL = "SELECT myField1,myField2 FROM myTable WHERE myKeyField = '".intval($_GET['id'])."'";
$QRY = mysql_query($SQL);
$DATA = mysql_fetch_assoc($QRY);
?>
<form method='get' action='pageThatStoresData.php'>
<input type='hidden' name='key' value='<?php echo $_GET['id']; ?>' />
<input type='text' name='myField1' value="<?php echo $DATA['myField1']; ?>" />
<input type='text' name='myField2' value="<?php echo $DATA['myField2']; ?>" />
<button type='submit'>Submit</button>
</form>
So, this will give you a page that takes the data out of your table, displays it in a form with pre-filled values and on submit, will go to a URL like:
http://mydomain.com/pageThatStoresData.php?key=1&myField1=someData&myField2=someMoreData
In that page, you can access variables 'key', 'myField1', 'myField2' via the $_GET method.
Then you just need to update your table within that page:
$SQL = "UPDATE myTable
SET myField1 = '".mysql_real_escape_string($_GET['myField1'])."',
myField2 = ".mysql_real_escape_string($_GET['myField1'])."
WHERE key = '".intval($_GET['key'])."'
";
$QRY = mysql_query($SQL);
PLEASE NOTE: The code above is unsuitable for a straight copy/paste as it doesn't do any error checking etc, its purely a functional example (and typed straight in here so I apologise if there are any typos!).
Related
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
Being new to PHP and SQL, I have build a simple HTML form with 20 inputs, allowing users to enter specific data through input type=text or file. I have built a mysql database where this user data is inserted / saved. All is working, this is a major accomplishment for me.
I'm asking for help on this next step, I think this step would be called “edit”?
This step would allow users to recall the mysql data they entered, at a later time, to edit and save. Would like to have this recalled data injected directly into the original HTML form. Now, it seems necessary to have a method, (possibly a HTML form ”id “input), that calls from the data base, the specific record (including all 20 data inputs) that is associated with this user. Am I thinking correctly?
I'm asking for help / direction with simple yet detailed approach to solve this step. Note, my few attempts at this “edit” step, using some examples, have failed. I do not have a firm grasp of this PHP, yet have strong desire to become proficient.
This is a model, stripped down version of my current working code. I eliminated the $connection = mysql_connect.
This is the PHP I built, working great!
<?php
require('db.php');
if (isset($_POST['first_name'])){
$first_name = $_POST['first_name'];
$favorite_color = $_POST['favorite_color'];
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `form_data` (first_name, favorite_color, trn_date) VALUES ('$first_name', '$favorite_color', '$trn_date')";
$result = mysql_query($query);
if($result){
echo "<div class='form'><h1>First Name & Favorite Color POST to db was successfull.</h1>
<br/><h3>Click here to return <a href='https://jakursmu.com/tapcon_builder/tb_form_data_1.1.php'>TapCon Builder</a></h3>
</div>";
}
}else{
?>
This is the HTML user form, works great with the PHP script:
<div class="form">
<h1>First Name & Favorite Color "POST" to db Test</h1>
<form target="_blank" name="registration" action=" " method="post">
<p> First Name<input name="first_name" type="text" placeholder="First Name" /> </p>
<p> Favorite Color <input name="favorite_color" type="text" placeholder="Favorite Color" /> </p>
<p> <input type="submit" name="submit" value="Submit / Update to db" /></p>
</form>
</div>
Suppose the user queries the database using their “first_name”, when this “edit” step is completed, the final result will render / inject the users “first_name” and “favorite_color” back into the original HTML form. Does this make sense?
The database I created for this help post, looks like this:
database image
When a user wishes to edit their data, they can enter their "first_name", in a form text input, (im assuming?) where their "first_name" will be found in the data base. The ouutput result of this database query will be injected into the original form, ready for any user edit.
User Edit for: Results (in origingal form):
Jack Jack Black
Jeff Jeff Green
Randall Randall Red
So on.........
I hope this explanation makes sense where any experienced help or direction is offered.
Thanks for viewing!
just for practice purposes, but can look into prepared statements at you liesure time.
first create ur php file
<form method="post" action="edit.php">
<?php
//in ur php tag. select items from the row based on an id you've passed on to the page
$sql = "select * from 'form_data' where blah = '$blah'";
$result = mysqli_query($connection, $sql);
if($result){
$count = mysqli_num_rows($result);
if($count > 0) {
while($row = mysqli_fetch_assoc($result)){
$name = $row['firstname'];
$lname = $row['lastname'];
//you can now echo ur input fields with the values set in
echo'
<input type="text" value="'.$name.'" >
';//that how you set the values
}
}
}
?>
</form>
Finally you can run and update statement on submit of this you dynamically generated form input.
Also please switch to mysqli or pdo, alot better that the deprecated mysql.
look into prepared statements too. Hope this nifty example guides you down the right path...
i need an help from you all.
i had created an form using PHP. it's a school application registration form. it has one page only.
i need to generate registration number(session id used as registration number here) for everyone who opens the form.
instead of creating a session i have used ID for all. that is when some one submits the form, it checks the DB and if the registration number is there, it will increment one value and add the current form to DB.
my code here
<td>Application No : <input type="hidden" name="disablusr_dummyid" autocomplete="off" style="background:#f0efed;" value="00<?php
include('config.php');
$q="select MAX(auto_gen_id) from application_form";
$result=mysql_query($q);
$data=mysql_fetch_array($result);
$max_val=$data[0];
echo $max_val+1;
?>"/>
<input type="hidden" name="applicant_id" autocomplete="off" value="00<?php
include('config.php');
$wer = "select MAX(auto_gen_id) from application_form";
$resultgh = mysql_query($wer);
$dates = mysql_fetch_array($resultgh);
$erfdqwe = $dates[0];
echo $erfdqwe+1;
?>" />
<input type="hidden" name="txt_applicant_id" style="display:none;" autocomplete="off" value="<?php
include('config.php');
$werqw = "select MAX(auto_gen_id) from application_form";
$resultghasw = mysql_query($werqw);
$dataqsax = mysql_fetch_array($resultghasw);
$erfdqweqti = $dataqsax[0];
echo $erfdqweqti+1;
?>" /></td>
but what is happening is when multiple users are using the form same session ID is generated and only one user is able to save the form and it reflects in DB. other forms are being not submitted and not added to DB.
help me in this error.. thanks in advance.
The solution here is not the use the hidden fields for the IDs :
At this moment u have something like this :
"INSERT INTO (id, ..., ...) VALUES('".addslashes($_POST['applicant_id']."', ...)
You should refactor your logic to calculate the id afterwards meaning that u drop the hidden fields and do this :
<?php
if (!empty($_POST)) {
$wer = "select MAX(auto_gen_id) from application_form";
$resultgh = mysql_query($wer);
$dates = mysql_fetch_array($resultgh);
$erfdqwe = $dates[0];
$new_applicant_id = $erfdqwe+1;
}
And then use the $new_applicant_id into the INSERT sql.
On a sidenote your code is vulnerable for SQL injection and is using outdated functions.
You should try to move to mysqli or PDO and preferable use prepared statements
I have a button on a webpage that allows users to add a video on that page to their list of favourites. behind this button is a form and some php. The PHP code uses a session variable to retrieve the username. This information is used to get the relevant user id from the database and store its value in a variable. Using the input value from the form it was possible to retrieve the tuple from the videos database table that related to the video in question and store the values of the video title and URL attributes in variables. The code then checks if the user has already added the video as a “favourite”. The favourites database entity is checked for tuples containing both the user id and video id. If both are contained in a single row of the database table the user has already added the video and is notified of this. Otherwise, the user id, video id, video title and URL are inserted into the favourites database entity and the user is informed that the video has been added
this all works fine in chrome or safari but does nothing in ie or firefox. The database is updated and message is displayed only in Chrome and safari. I've attached the code, please note the session has already been started in earlier code on the webpage. Any assistance would be greatly appreciated.
<div id="addfav">
<form action="python.php" method="post">
<input name="add" src="images/add.png" type="image"
value="3">
</form>
<?php
$user=$_SESSION['user'];
if ( isset( $_POST['add'] ) )
{
$vid = $_POST["add"];
$sql = "SELECT * FROM `users` WHERE username = '$user'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
$uid= $row['user_id'];
$sql = "SELECT * FROM `Video` WHERE Video_id = '$vid'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
$url=$row['URL'];
$title=$row['Title'];
$check = mysql_query("SELECT * FROM `favourites` WHERE Uid = '$uid' AND vid_id = '$vid'") or die (mysql_error());
$r = mysql_num_rows($check);
if ($r>=1)
{
echo "already added to favourites";
echo '<script type="text/javascript">window.alert("Already added to favourites")</script>';
//'<span style="color: red;" />Already added to favourites </span>' ;
}
else
{
mysql_query("INSERT INTO `favourites` (`Uid`,
`vid_id`,`url`,`title`) VALUES ('$uid',
'$vid','$url','$title')")or die(mysql_error());
echo "Added to favourites";
}
}
?>
</div>
(Just a debug idea) Try to change your input image to a hidden element like this :
<form action="python.php" method="post">
<!-- I don't remove this, to keep the image shown-->
<input name="addimg" src="images/add.png" type="image" value="3">
<input type='hidden' name='add' value='3' />
</form>
Does it works now?
PHP is run server-side. This means that regardless of what browser you're using, it works as expected. The problem is definitely from HTML codes you've written if IE and Firefox can connect to your website without any problem.
I think the problem is inside your form tag because I think it's not standard you can either use a GET method inform that your form is submitted, or use a hidden input indicating it.
P.S. I think your code has security issues. (SQL Injection)
When user clicks on <input type="image" /> browser will pass coordinates of a click. Chrome will send three values:
add.x = x_coord
add.y = y_coord
add = input_value (3 in your case)
Note that in php you can access add.x/add.y value with $_POST["add_x"]/$_POST["add_y"] (see dot replaced with underscore)
At the same time, IE will not pass third value. That is why your if ( isset( $_POST['add'] ) ) will never return true. Option is to put video id value into some hidden field and use its name in that if.
You can easily check that behavior by doing var_dump($_POST); in php
PS:
You should never use values received in request without them being sanitized in sql queries. Right now code below is opened to sql injections:
$sql = "SELECT * FROM `Video` WHERE Video_id = '$vid'";
You should, at least, user mysql_real_escape_string function before value is inserted into a query:
$sql = "SELECT * FROM `Video` WHERE Video_id = '".mysql_real_escape_string($vid)."'";
And take a look at warning message on top of php manual page linked above: mysql_* functions are deprecated and you should better use PDO or mysqli extension.
HI everyone
I have a html application form which have username,password,age etc .NOw i am able to store these values into database without any problem.Now i want to add a edit button if user want to edit his profile..
1.First tell me where i should put this Edit Button.I think i should place it into user'home page where he is redirected after confirming username and password...
Now i want to know how he can do edit opearation in existing data which is stored in database.
I know very well how to retrive data from database.Now tell me in which form this data should be retrived from database..Should i retrive it in that application form agina(how) or i should retrive it in a file(but then how to send back).
I have no idea what to do and please tell me how this data will be updated(i think at the place of insert command i should use update command)..Plz tell me in deatil.I will be thankfull to you
By my opinion the edit ubtton must be in the user profile.
As for the update - create primary key ofr one of the columns and update by it, something like
$sql = 'UPDATE table SET username='.$user_name.', password ='.$pass.' WHERE id = '.$user_id
Dont forget to make server side validation of the data too.
Here is simple solution:
<?php
if(isset($_GET['user_id'))
{
$sql = 'SELECT id, username, password from users_table WHERE id='.$users_id;
if ($result = $mysqli_object->query($sql)) {
$row = $result->fetch_assoc()
}
echo '<form action="" method="post">';
echo '<input type="text" name="username" value="'.$row['username'].'"';
echo '<input type="password" name="password" value="'.$row['password'].'"';
echo '<input type="hidden" name="id" value="'.$row['id'].'"';
echo '<input type="submit" value="save" />';
}elseif(isset($_POST['id'])){
$user_name = $_POST['username'];
$pass = $_POST['password'];
$user_id = $_POST['id'];
$sql = 'UPDATE table SET username='.$user_name.', password ='.$pass.' WHERE id = '.$user_id
if($result = $mysqli_object->query($sql))
echo 'Profile updated';
else
echo $mysqli_object->error;
}else{
echo 'You are not supposed to be on this page!';
}
?>
I haven`t tested it so it could have any syntax mistakes. You can read a little bit more for the mysqli (MySQL Improved Extension) in the PHP documentation.
If you are trying to develop an application(not just playing with PHP) you should better try some of the available free frameworks, they will do most of the work instead of you.
Good luck