Query not updating not sure why - php

For some reason this script isn't updating the database properly according to the query. Does anybody have any idea why the script isn't updating? Please let me know!
<?php
session_start();
include '../connect.php';
if(!isset($_SESSION['id'])){
header("Location: ../index.php");
}
if(isset($_POST['submit'])){
$id=$_POST['id'];
$postid=$_POST['postid'];
$content=$_POST['content'];
$title=$_POST['title'];
echo "<pre>";
print_r($_POST);
if(!empty($content)){
$content = mysql_real_escape_string($content);
} else {
echo 'You need to write something in your comment!';
}
$upd=mysql_query("UPDATE replies SET reply_content='$content' WHERE reply_id='$postid'");
if(!$upd){
echo 'Error: '.mysql_error();
}
} else {
if (isset($_GET['id'])){
$postid = $_GET['id'];
$id=$_SESSION['id'];
$q = mysql_query("SELECT * FROM `replies` where `reply_id`='$postid'");
if(!$q){
echo 'Error: '.mysql_error();
}
$res = mysql_fetch_assoc($q);
$q2 = mysql_query("SELECT topic_subject FROM `topics` where `topic_id`='$postid'");
$res2 = mysql_fetch_assoc($q2);
if(!q2){
echo 'Error: '.mysql_error();
}
if ($res['reply_by'] == $id){
} else {
header("Location: ../pagenotfound.html");
}
}
?>
<form action="edit.php">
<input type="text" name="title" value="<?php echo $res2['topic_subject'] ?>" disabled="disabled" />
<br />
<textarea rows="20" name="content" cols="50"><?php echo $res['reply_content']?></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
}
?>
If you need more info let me know!
Update: The issue is that when I click submit, it sends me to a page which still lists the form. I noticed this isuee when I tried to print_r($_POST) because it didn't actually print $_POST, I believe there is something wrong with either the form or where it checks if isset submit.

Try with:
if(!empty($content)){
$content = mysql_real_escape_string($content);
} else {
echo 'You need to write something in your comment!';
// if $content is mandatory, you should put a die("error") here
}
You should check your $_POST array with a simple
echo "<pre>";
print_r($_POST);
and ensure that POST has vars you are looking for (first of all: submit)
EDIT: put print_r($_POST) BEFORE using it just before:
if(isset($_POST['submit'])){
ERROR: you forgot to set form method type. Try with:
<form action="edit.php" method="post">
Without that, form will send parameters as $_GET.
Here's a simple php-form tutorial. http://php.net/manual/en/tutorial.forms.php

Related

I want users to update account information only after they log in... But I have no Idea How to do it

I have made simple php files by using which I can validate username and PASSWORD and then only user can log in. I want users to update account only if they log in to account. Without validating ID and password, they can't update their Name and Surname and all... It's very simple program. Here is the table Structure.
It is just a Demo data. I want users to update their accounts only after logging in. Here is the file by which they can see their information by logging in.
<html>
<head>
<title>
Login
</title>
</head>
<body>
<?php
if(isset($_POST["uname"]) && isset($_POST["pass"]))
{
$uname=$_POST["uname"];
$pass=$_POST["pass"];
mysql_connect("localhost","adarsh","Yeah!");
mysql_select_db("aadarsh");
$select = mysql_query("select * from users where username='$uname' AND pass='$pass'");
$data = mysql_fetch_array($select);
if($uname==$data['username'] && $pass==$data['pass'])
{
echo "<center>";
echo "Name: ".$data['username']."<br>";
echo "Last namme: ".$data['lastname']."<br>";
echo "<img src=".$data['image']."><br>";
echo "</center>";
}
else
{
echo "<script>alert('Nope!!!');</script>";
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="uname">
<input type="pass" name="pass">
<input type="submit" name="submit" value="Login!">
</form>
</html>
The code is working fine and They can see their data by entering username and password. If they will enter wrong Username and password, they will just see alert box.
I just want users to update their data after logging in. Without login, they can't update their data.
But i have no idea how to do it. Once I tried by validating username and password and then redirecting to new page where they can update their account using header location but that doesn't work. I didn't get any variables on the other page.
Help me solving this....
Try this
<html>
<head>
<title>
Login
</title>
</head>
<body>
<?php
session_start();
if(isset($_POST["submit"]))
{
$uname=$_POST["uname"];
$pass=$_POST["pass"];
if(empty($uname) && empty($pass))
{
echo "<script>alert('Empty');</script>";
}
else
{
mysql_connect("localhost","adarsh","Yeah!","aadarsh");
$select = mysql_query("select * from users where username='$uname' AND pass='$pass'");
$data = mysql_fetch_array($select);
$count = count($data);
if(empty($count) || $count > 1)
{
echo "<script>alert('Invalid Login');</script>";
}
else
{
$image = $data['image'];
$lname = $data['lastname'];
$username = $data['username'];
$_SESSION["lastname"] = $lname;
$_SESSION["username"] = $username;
echo "Name: ".'$username'."<br>";
echo "Last namme:".'$lname'."<br>";
echo "<img src='$image'><br>";
if(isset($_SESSION))
{
redirect('new_page.php');
}
else
{
echo "<script>alert('Something Went Wrong');</script>";
}
}
}
}
?>
<form method="post" action="#">
<input type="text" name="uname">
<input type="pass" name="pass">
<input type="submit" name="submit" value="Login!">
</form>
</body>
</html>
and in new_page.php
<?php
session_start();
if(isset($_SESSION["username"]))
{
//show update form
}
else
{
//redirect to login page
redirect('login.php');
}
Includes
Using Session
Optimize Query
Validate all fields
and take a look at this too
How can I prevent SQL-injection in PHP?
MySQL extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
So, after logging in, instead of simply displaying the users details, display a form allowing the user to update their details, something like this (incomplete code just to give you an outline):
if($uname==$data['username'] && $pass==$data['pass'])
{
echo '<form method="" action ="">';
echo '<input value="'.$data['username'].'" />';
echo '<input value="'.$data['lastname'].'" />';
echo '<input type="submit" />';
echo "</form>";
}
If you want to pass variables from one page to another, once the user is logged in, you should use Session variables.
Thanks to all to answer on my question. Finally with the help of you guys, I solved every errors and Program is working fine!
I did this with the help of 2 files... Here are they,
updatedata.php (This file contains only html stuff... .html will also work)
<html>
<head>
<title>
Login
</title>
</head>
<body>
<form method="post" action="updateaccount.php">
Username : <input type="text" name="uname"><br>
Password :<input type="password" name="pass"><br>
New Information:<br><br>
New Name : <input type="text" name="newname"></input>
<input type="submit" name="submit" value="Update!">
</form>
</html>
updateaccount.php (hehe, Don't get confused in file names...)
<?php
$con=mysql_connect("localhost","adarsh","Password");
mysql_select_db("aadarsh",$con);
if(isset($_POST["uname"]) && isset($_POST["pass"]))
{
$uname=$_POST["uname"];
$pass=$_POST["pass"];
}
$sql="select * from users where username='$uname' AND pass='$pass'";
$select = mysql_query($sql);
$data = mysql_fetch_array($select);
$username=$_POST["newname"];
if(isset($_POST['submit']))
{
if($uname==$data['username'] && $pass==$data['pass'])
{
$user_id= $data['id'];
if(isset($_POST['newname']))
{
$update = mysql_query("UPDATE users SET username = '$username' WHERE id = $user_id");
if($update)
{
echo "<script>alert('updated!');</script>";
header("location:http://www.example.com");
}
else
{
echo mysql_error();
}
}
}
else
{
echo "<script>alert('Nope!!!');</script>";
}
}
?>
Thanks to all of you again.... :)
Some considerations about your code:
mysql_connect is deprecated, you should use mysqli_connect.
http://php.net/manual/en/book.mysqli.php
You can use empty() instead of isset(). empty() will return true if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable. With !empty you can:
if (!empty($_POST["uname"]) && !empty($_POST["pass"])){
$uname = .........
}
Can't use echo and header("location:http....") in the same loop. If you send to another page, the message will not be displayed.
After a header("location:http....") you must exit(); otherwise, the code will follow the normal flow.
You check if ($update). If you click the submit button, $update always be true, so this check is not necessary.
Hope that helps.

Keep text in text field after submitting

I am having a issue keeping text in the text field that was previously there after pushing submit. I am using this:
<input name="date" type="text" id="date" <?php if(isset($_POST['date'])){echo 'value="'.$_POST['date'].'"';} ?>/>
I also have this on successful submit so that it reloads the table but also removes whats above because it's refreshing.
echo "Succesfully added transaction. Updating table...";
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"6\">";
My entire code=
<?php
// if ('POST' === $_SERVER['REQUEST_METHOD'])
if (isset($_POST['submit2']))
{
$con = mysql_connect("xx","xx_xx","xx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xx_xx", $con);
$date = $_POST['date'];
$_SESSION['date'] = $_POST;
//Writes the to the server
$sql = mysql_query("INSERT INTO `reservation__date` (`reservation_id`, `reservation_date`)
VALUES
('000', '$date')") or die(mysql_error());
$query = mysql_query($sql);
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$_SESSION['DATE'] = $_REQUEST['date'];
echo "Succesfully added transaction. Updating table...";
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"6\">";
mysql_close($con);
}
}
?>
If you follow the PRG principle (POST-redirect-GET), you need to track the POST data in the session.
I assume your do something like this after submit:
if (POST is fine) {
do something;
redirect;
} else {
re-render page and show feedback
}
Since the server will discard any POST data on redirect, you need to track the POST data on every submit and re-populate the POST data on page load (GET).
$_SESSION['user_POST'] = $_POST;
if (POST is fine) ...
On your page that contains the form to submit:
if (isset($_SESSION['user_POST']) {
$_POST = $_SESSION['user_POST'];
}
Ignore syntax, I'm not into PHP that much.
FOR TESTING
<?php echo $_POST['date']; ?>
try setting to is equal to true if the above is right
<input name="date" type="text" id="date" <?php if(isset($_POST['date']) === true){echo 'value="'.$_POST['date'].'"';} ?>/>
Here is your requirement
<?php
session_start();
if(isset($_REQUEST['date'])){
$_SESSION['date'] = $_REQUEST['date'];
echo "Succesfully added transaction. Updating table...";
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"6\">";
}
?>
<form method="post">
<input name="date" type="text" id="date" value="<?php echo $_SESSION['date'];?>" />
<input type="submit" name="submit" />
</form>
if you are using session variable.. use session_start(); at top of you page..
check if you have method="POST" in the form because by-default its GET..
check weather you have correct action field for the form such as <form action="abc.php">
if you want to put text in value, better check the condition within the value attribute and echo the value. because even if you don't write value in HTML insert tag.. It take as value="" . which creates an ambiguous condition later.
so better do
<form action="abc.php" method="post" >
<input name="date" type="text" id="date" value="<?php if(isset($_POST['date'])){echo $_POST['date'];} ?>" />
.......................
</form
and now on abc.php
<?php
session_start(); // as you are using session variables..
if (isset($_POST['submit2']))
{
$con = mysql_connect("xx","xx_xx","xx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xx_xx", $con);
$date = $_POST['date'];
$_SESSION['date'] = $_POST['date']; // POST is an array carrying many elements so be specific which element you want. inthis case it is $_POST['date'];
//Writes the to the server
$sql = mysql_query("INSERT INTO `reservation__date` (`reservation_id`, `reservation_date`) VALUES ('000', '$date')") or die(mysql_error());
$query = mysql_query($sql);
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$_SESSION['DATE'] = $_REQUEST['date'];
echo "Succesfully added transaction. Updating table...";
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"6\">";
mysql_close($con);
}
}
?>
hope this will help you...

get result in same page and form

hello i have simple problem with my functions there is 2 codes :
i need when i put the right input answer echo $row['answer']; and sucess in next code.
it means i need when $_POST['answer'] = $row['answer']; echo my password
can someone help me with if cond.
this code is working perfect :
<?php
$username = $_POST['username'];
include('config.php');
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
while($row = mysqli_fetch_array($result)){
echo $row['username'];
echo "</br>";
echo "</br>";
echo "<p><b>Secret Question</b></p>";
echo $row['secret'];
$freeanswer = $row['answer'];
}
?>
code problem in same page :
</br>
</br>
<form action="" method="POST">
<p><b>Answer is :</b><p>
<input type="text" name="answer">
</br>
</br>
<input type="Submit" value="Submit">
</form>
</div>
<?php
$anme = $_POST['answer'];
if ($anme==$freeanswer) {
echo "sucess";
} else {
echo "wrong";
}
?>
Do you have problem sending the data?
If you want to post the form data to the same page you could use this:
<form action="<?php echo $_SERVER['REQUEST_URI'];?>" method="post">
And this code will catch whatever you posted. (Put it in the same page as the form)
<?php
if(isset($_POST['answer'])) {;
if($name==$freeanswer) {
echo "success";
} else {
echo "wrong";
}
} else {
// Just for testing
var_dump("No data sent yet");
}
?>
Where is the $freeanswer variable declared in the second code?
This if statement is failing cause there is no $freeanswer declared.
$anme = $_POST['answer'];
if ($anme==$freeanswer) { ..
I see you declared it in first code but I dont see it in the second code..
EDIT :
Actually I didn't see It's all the same code. But still the problem is $freeanswer cause It's not declared in public scope It's only in the scope of while loop
Try declaring / writing this line of code here :
$username = $_POST['username']; // Near this line
$freeanswer = ""; // Declare this here
You should put a name to submit button, and the check the existence of $_POST['name_of_button'];
This is a dirty example I wrote quickly so you can get the idea, I didn't test it
<?php
// if the button has not been sent show the form
if(!isset($_POST['submit'])) {
?>
<form action="/test.php" method="POST">
<p><b>Answer is :</b><p>
<input type="text" name="answer">
</br>
</br>
<input type="Submit" value="Submit" name="submit">
</form>
</div>
<?php
// otherwise means the form has been sent, show the password or wrong
} else {
include('config.php');
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
$row = mysqli_fetch_array($result);
if($row) {
if($row['answer'] == $_POST['answer']) {
echo 'your password is ' . $row['password'];
} else {
echo 'wrong!';
}
}
}

Retrieve data from database and display in text fields.

Please help me. I written a code but it is not working well.
I want to retrieve data from database and display text fields.
My Code is:
<DOCTYPE html>
<html>
<head><title>Practice</title></head>
<body align="center">
<?php
$con=mysqli_connect("localhost","root","","address_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<form action="1.php" method="post">
Name <br><input type="text" name="name" value="<?php echo $_GET['n']; ?>"><br>
Address 1<br><input type="text" name="address_1" value=""><br>
Address 2<br><input type="text" name="address_2" value=""><br>
Address 3<br><input type="text" name="address_3" value=""><br><br><br>
<input type="submit" name="reset" value="Clear">
<input type="submit" name="submit" value="Submit">
<input type="submit" name="retrieve" value="Retrieve">
</form>
<?php
if (isset($_POST['submit']))
{
$name=$_POST['name'];
$address_1=$_POST['address_1'];
$address_2=$_POST['address_2'];
$address_3=$_POST['address_3'];
if(($name=='')||($address_1=="")||($address_2=="")||($address_3==""))
{
echo "<script>alert('Please fill all fields')</script>";
exit();
}
else
{
mysqli_query($con,"INSERT INTO address_tbl (name,address_1,address_2,address_3)
VALUES ('$name','$address_1','$address_2','$address_3')");
echo "<script>alert('Your record successfull inserted into database...')</script>";
exit();
}
}
if (isset($_POST['retrieve']))
{
$result = mysqli_query($con,"SELECT * FROM address_tbl");
while($row = mysqli_fetch_array($result))
{
$name=$row['name'];echo "<br>";echo "<br>";
$add1=$row['address_1'];echo "<br>";echo "<br>";
$add2=$row['address_2'];echo "<br>";echo "<br>";
$add3=$row['address_3'];echo "<br>";echo "<br>";
echo "<script type='text/javascript'>
window.open('1.php?n=$name','_self'); </script>";
}
}
?>
</body>
</html>
Please help me. give me any hint that I can solve my problem. Thanks
try this ,
mysqli_query($con,"INSERT INTO `1address_tbl` (`name`,`address_1`,`address_2`,`address_3`)
VALUES ('$name','$address_1','$address_2','$address_3')");
it should work fine now. it needs to include ( ` ) around the table names and column name to make sql work correctly. you left them out,
you replace this with yours.
First of all you should have your php in a seperate file called index.php with just php code then create a page called index.html.php in that page use a foreach loop to output data from the database its the most common and practical way of doing what your trying to do .

PHP webpage has a direct loop error?

I have been trying to create a login page in PHP to no avail though, i have been getting a "This webpage has a redirect loop" error when i try to run it, so i was wondering if anyone could possibly spot my mistakes? Here is my code:
<?php
require_once("nocache.php");
$id = $_POST["id"];
$pword = $_POST["pword"];
if (!empty($_POST){
if (!empty($id) || !empty($pword)){
require_once("dbconn.php");
$sql = "select username, school_type from school_info where username = '$id' and password = '$pword'";
$rs = mysql_query($sql, $dbConn);
if (mysql_num_rows($rs)> 0 ) {
session_start();
$_SESSION["who"] = $id;
$_SESSION["school_type"] = mysql_result($rs,0,"school_type");
header("location: EOI_home.php");
}
}
else {
header("location: login.php");}
} else {
header("location: login.php");}
?>
<form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="login">
ID: <input type="text" name="id" /><br/>
pword: <input type="password" name="pword" /><br/>
<input type="submit" value="log in" />
<input type="reset" />
</form>
All of the answers given are technically correct, the way you've set your logic is incorrect... take the following example and port it across into your own code.
<?php
$id = $_POST["id"];
$pword = $_POST["pword"];
if(!empty($_POST)) {
// The form was submitted, perform validation here.
if(!empty($id) || !empty($pword)) {
// Form validation passed, insert into database
} else {
// Form validation failed, display an error or redirect back
}
} else {
// Form was not submitted, so display the form.
}
?>
Edit
I was hoping not to have to do the work for you (since it's best you learn) but perhaps seeing the above code, and the below code you can learn from it that way?
<?php
require_once("nocache.php");
$id = $_POST["id"];
$pword = $_POST["pword"];
if(!empty($_POST)) {
if(!empty($id) || !empty($pword)) {
require_once("dbconn.php");
$sql = "select username, school_type from school_info where username = '$id' and password = '$pword'";
$rs = mysql_query($sql, $dbConn);
if(mysql_num_rows($rs) > 0) {
session_start();
$_SESSION["who"] = $id;
$_SESSION["school_type"] = mysql_result($rs, 0, "school_type");
header("location: EOI_home.php");
}
} else {
header("location: login.php");
}
}
?>
<form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="login">
ID: <input type="text" name="id" /><br/>
pword: <input type="password" name="pword" /><br/>
<input type="submit" value="log in" />
<input type="reset" />
</form>
The loop is here:
$id = $_POST["id"];
$pword = $_POST["pword"];
if (empty($id) || empty($pword)){
header("location: login.php"); }
If the $_POST values are not set, the redirect happens. Since you are not setting the values before the redirect, it happens again. And again. And again...
To correct this problem, display your form if the $_POST values are not set.

Categories