I can't get my update query to work (php / mysqli) - php

I am posting a shortened version of the form and updating lines. I will truly appreciate any help. I have spent the last 48 hours trying all I could think of and it's driving me insane. If I remove the line if($_SERVER["REQUEST_METHOD"]=="POST"), the program runs on loading the page and does update the table at the ID in the url with a blank field. Thanks in advance. Here's the code:
<?php
$id = $_GET['id'];
$user = $_SESSION['user'];
Echo '<form action="editone.php" method="POST">
Enter new name:<input type="text" name="namex" />
<input type="submit" name="Submit" value="Update List" /> </form>';
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $id);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>

I think your form action didn't pass id.
<form action="editone.php" method="POST">
If you're using this single file as form editor and action, your form editor URL should be http://localhost/editone.php?id=1
Try to change your form action to
<form action="editone.php?id='.$_GET['id'].'" method="POST">
or just leave the action blank
<form action="" method="POST">

Ok - maybe I'm way off base here but I see the following problems.
1) Your method is POST however your id is coming from GET.
2) I don't see where the id is coming from. It could be coming from somewhere and not posted but I don't see it.
Have you checked to verify the value is actually being passed through to the php?
try this
echo "GET = " . var_dump($_GET);
echo "<br><br>";
echo "POST = " . var_dump($_POST);
exit();
Post the results and then post where the id is coming from if you can't figure it out still. :)

Use the below code:
$query = "SELECT now_edit, FROM EDITORIES WHERE edit_id='$numb' LIMIT 1";

I assume your page is being called initially from an anchor link on another page which is why you are getting the id from $_GET['id'].
When the user presses the submit button of course the form is being submitted as a POST so all the data will be in $_POST, therefore $_GET['id'] will fail and should be generating an error message.
You need to save the $_GET['id'] from the first instantiation so you can use it when the form is posted to you. So put it in a hidden field that will be posted to you with the post
<?php
session_start();
$user = $_SESSION['user'];
if($_SERVER["REQUEST_METHOD"]=="GET") {
if ( isset($_GET['id']) ) {
$id = $_GET['id']);
} else {
// no param passed, could be a hack
header('Location: some_error_page.php');
exit;
}
echo '<form action="editone.php" method="POST">';
echo '<input type="hidden" name="id" value="' . $id . '">';
echo 'Enter new name:<input type="text" name="namex" />';
echo '<input type="submit" name="Submit" value="Update List" /></form>';
}
if($_SERVER["REQUEST_METHOD"]=="POST") {
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $_POST['id']);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>

Related

Can't update form data

I am trying to edit form data by displaying the previous saved data on the form and then update it. It shows the data on the form which is saved in database but when i enter the new data it does not get the id of the row. I echo the update query, it shows the changed values but it shows id equals to empty. Here is my code for edit record and update; Edit record is working but update isn't:
<?php
include('connection.php');
$id = '';
if( isset( $_GET['id'])) {
$id = $_GET['id'];
}
$udfname = mysql_real_escape_string($_POST["udfname"]);
$udlname = mysql_real_escape_string($_POST["udlname"]);
$udpwd = mysql_real_escape_string($_POST["udpwd"]);
$udeml = mysql_real_escape_string($_POST["udeml"]);
$udnum = mysql_real_escape_string($_POST["udnum"]);
$query="UPDATE form
SET fname = '$udfname', lname = '$udlname', pwd = '$udpwd', eml = '$udeml', num = '$udnum'
WHERE id='$id'";
$res= mysql_query($query);
if($res){
echo "<p> Record Updated<p>";
}else{
echo "Problem updating record. MY SQL Error: " . mysql_error();
}
?>
Form for editing record:
<?php
include('connection.php');
$id = (int)$_GET['id'];
$query = mysql_query("SELECT * FROM form WHERE id = '$id'") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
echo "";
$fname = $row['fname'];
$lname = $row['lname'];
$pwd = $row['pwd'];
$eml = $row['eml'];
$num = $row['num'];
}
?>
<html>
<head>
<title>Edit</title>
<script>
'
'
Jquery code here
'
'
</script>
</head>
<body>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?=$id;?>">
First Name: <input type="text" name="udfname" value="<?=$fname;?>"><br>
Last Name: <input type="text" name="udlname" value="<?=$lname?>"><br>
Password: <input type="text" name="udpwd" value="<?=$pwd?>"><br>
Email: <input type="text" name="udeml" value="<?=$eml?>"><br>
Contact Number: <input type="text" name="udnum" value="<?=$num?>"><br>
<input type="Submit">
</form>
</body>
</html>
At update time your form is submitted using POST request. So you need to get ID using POST method. So to get ID of hidden field change your code as below:
$id = '';
if( isset( $_POST['ID'])) {
$id = $_POST['ID'];
}
Please try below code
if( isset( $_POST['id']) && $_POST['id']!=null) {
$id = $_POST['id'];
}
Dear i think the problem with your method you are sending the data using post method and its very simple instead of this code
if( isset( $_GET['id'])) {
$id = $_GET['id'];
}
write
if( isset( $_POST['id'])) {
$id = $_POST['id'];
}
and one more thing that is you are using the mysql deprecated function for database kindly use the pdo for this or new mysqli functions.

POST Data not inserting into sql table

I am using a form. (I wanted the message text as a text area but changed back to normal text to see if this was the problem)
This is the form I am using
<form name="addmessage" method="POST" action="addmessage.php" >
<input type="text" name="message_title" id="message_title">Message Title</input>
<input type="text" name="message_text" id="message_text">Message</input>
<input type="submit" name="submit" value = Add>
</form>
Below is the PHP code. I understand i need to protect against sql injection however, i can do this later.
<?php
include_once("config.php");
if(isset($_POST["message_title"]) && strlen($_POST["message_title"])>0)
{
$message_title=$_POST['message_title'];
$message_text=$_POST['message_text'];
session_start();
$barber_id = $_SESSION['barber_id'];
$insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."',".$message_text.")");
}
else
{
//Output error
header('HTTP/1.1 500 Error You have left it blank');
exit();
}
header("location:messages.php");
?>
If manually enter data using phpMyAdmin, I can get it to display using the code below.
include_once("config.php");
session_start();
$barber_id = $_SESSION['barber_id'];
$results = $mysqli->query("SELECT * FROM messages WHERE barber_id ='$barber_id' ");
//get all records from table
while($row = $results->fetch_assoc())
{
$prices_id = $row['prices_id'];
echo '<div data-role="collapsible">';
echo '<h1>';
echo ' Message Title: ';
echo $row['message_title'];
echo '</a>';
echo '</h1>';
echo '<p>';
echo $row['message_text'];
echo ' Delete</div>';
}
$mysqli->close();
?>
At $insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."',".$message_text.")");
you should write
$insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."','".$message_text."')");
Everytime you pass a String or other non int values you must pass them like that: 'xx', otherwise mysql will see it as query param and it crashes.

Login Page Not Connected to Registration page

the registration form is connected to the database via db.php but I am having trouble in submitting the login details.
<html>
<head>
<?php
include('db.php');
$username = #$_POST['username'];
$password = #$_POST['password'];
$submit = #$_POST['submit'];
the main problem is after the submit button is clicked by an existing user it should give the message but there's problem in the if statement, because on the wamp server its showing only the else message i.e. Error.
if ($submit)
{
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
if (mysql_num_rows($result)) {
$check_rows = mysql_fetch_array($result);
$_POST['username'] = $check_rows['username'];
$_POST['password'] = $check_rows['password'];
echo "<center>";
echo "You are now Logged In. ";
echo "</center>";
}
else {
echo "<center>";
echo "No User found. ";
echo "</center>";
}
}
else echo "Error";
?>
</head>
<body>
<form method="post">
Username : <input name="username" placeholder="Enter Username" type="text"><br></br>
Password : <input name="password" placeholder="Enter Password" type="password"><br>
<input type="submit" value="Submit">
</body>
</html>
You want get $_POST with name submit, but do not send it to the form
Try change
<input type="submit" value="Submit">
to
<input type="submit" name="submit" value="Submit">
Firstly this is old style of php/mysql. So look at PDO on php.net seeing as you are setting out on new project it really wont be hard to make the change now rather than later.
Now onto your issue. if you intend on carrying on with your old method try this.
$sql = "SELECT * FROM user WHERE username=' . $username . ' AND password=' . $password . '";
// check the query with the die & mysql_error functions
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_num_rows($query);
// checking here equal to 1 In a live case, for testing you could use >= but not much point.
if ($result == 1) {
// Checking needs to be Assoc Now you can use the field names,
// otherwise $check_rows[0], $check_rows[1] etc etc
$check_rows = mysql_fetch_assoc($query); // oops we all make mistakes, query not result, sorry.
// This is bad but for example il let this by,
// please dont access user supplied data without
// validating/sanitising it.
$_POST['username'] = $check_rows['username'];
$_POST['password'] = $check_rows['password'];
} else {
// do not logged in here
}
The same in PDO
$sql=" Your query here ";
$pdo->query($sql);
$pdo->execute();
$result = $pdo->fetch();
if ($result = 1) {
// do login stuff
} else {
// no login
}
Remember though that you need to set up PDO and it may not be available on your server by default (older php/mysql versions) but your host should be happy enough to set them up.

PHP Form not directing to correct pages

I'm making a login page for the admins to make some changes to a website easily. However, the login page isn't working correctly. It won't go to the error page InvalidLogin.html and it won't go to the next page of the admin website AdminChanges.php.
Instead, I'm getting the following message:
Not Found
The requested URL /website/method="post" was not found on this server.
<?php
if ($_POST['submit'] == "submit")
{
$userName = $_POST['username'];
$passWord = $_POST['password'];
$db= mysql_connect("localhost", "root", "root");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("onlineform", $db);
$checkUserNameQuery = "SELECT username FROM onlineformdata ORDER BY id DESC LIMIT 1";
$checkUserName = mysql_query($checkUserNameQuery);
$checkPassWordQuery = "SELECT password FROM onlineformdata ORDER BY id DESC LIMIT 1";
$checkPassWord = mysql_query($checkPassWordQuery);
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
{
$AdminChanges = "AdminChanges.php";
}
else
{
$AdminChanges = "InvalidLogin.html";
}
}
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
<html>
<head>
<title>Admin Login</title>
</head>
<body>
<form action = <?php PrepSQL($AdminChanges); ?> method="post">
username: <input type="text" name="username" />
password: <input type="text" name="password" /> <br/>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
Two problems are joining forces to cause this error. First, your PrepSQL function does not echo the response, and neither does the code that calls it. You need to echo or print the response so that it appears in your generated HTML.
<?php echo PrepSQL($AdminChanges); ?>
Second, you need to encapsulate that value of the action attribute in double-quotes, like this:
<form action = "<?php echo PrepSQL($AdminChanges); ?>" method="post">
Also note that your code assumes that your mysql_query() statements were successful. For troubleshooting purposes, you should at least add an or die(mysql_error()) statement to the end of the mysql_query() lines. This will allow your code to provide some feedback when the query fails.
Additionally, please note that your query-handling method will never result in a valid login response.
$checkUserName = mysql_query($checkUserNameQuery);
$checkPassWord = mysql_query($checkPassWordQuery);
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
mysql_query() returns a MySQL resource, not a single field from the database. Your code attempts to compare that resource to the supplied username and password, and the comparison will always fail. For details about handling the results of mysql_query() see the documentation.
Replace:
PrepSQL($AdminChanges);
with:
print PrepSQL($AdminChanges);
Try this:
<form action = "<?php echo PrepSQL($AdminChanges); ?>" method="post">
You need to echo the value.
There are 2 errors I noticed:
Your $_POST['submit'] if statement doesn't let $AdminChanges be set for the form unless it has already been submitted.
To fix this you could change your if submit statement to just redirect to your invalid login page like so:
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
{
//Correct info do what you need to here
}
else
{
header("Location: InvalidLogin.html");
exit();
}
And also:
You need to change the action to go post to this page.
<form action="<? $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">

Database used to populate selection list

i am trying to create a form and in that form have a selection list in which the options are automatically populated with data from a database (namely customer's last names), after which when the last name is chosen from the list and the submit button is hit the "customer ID" that is related to that last name in the database will be submitted to another PHP file (task8.php) to be sent through further queries. I hope i have explained that all in an understandable manner. I have had a go at some code but i am really unsure on how to do this or if what i have written is on the right path.
Here is what i have written so far:
<body>
<?php
$conn = mysql_connect("localhost", "twa312", "dam6av9a");
mysql_select_db("warehouse312", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "select customerID, lastName from customer";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
$options= '<option value="0">Choose</option>';
while ($row=mysql_fetch_array($rs)) {
$id=$row["customerID"];
$name=$row["lastName"];
$options="<OPTION VALUE='" . $id . "'>" . $name ."</option>";
}
?>
<form method="GET" action="task8.php" id="custinfo" >
Choose name:<select name="lname" id="lname"><?php echo $options; ?>
</select>
<p><input type="submit" name="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</form>
What i am trying to do with the code is access the table "customer" and fields "customerID" and "lastName". Using the customer's last name as the option and the customer's ID as the options value in the selection list. Currently the code displays only a single name as an option in the selection list when it should display all the names in the database. Any help on this would be really great as i am fairly unsure.
There is an error in the code that I can see would cause PHP to generate notice error.
In the while loop you're using .= on the $options variable that isn't yet defined so PHP will barf on that.
Aside from that, it doesn't make sense to me that you're waiting for $_GET['submit'] to be set before iterating over the result set from mysql. As far as I can tell, the first time you'd hit this page there would be a single option in the select ("Choose"), and since the form submits to a different page I don't think you'd ever see a list of customer last names.
Finally, it's not really recommended to name your submit buttons 'submit', since when the page is parsed by the browser all the form elements of a specific form are created as attributes of that form, JS form objects have a 'submit' method so when you name an input 'submit' you clobber that value in the form object which makes it really hard to submit that form with JS.
First off move away from the mysql_functions.
Secondly create a model with all querys related to your customers that will handle fetching/puttin/updating the data related to your customer db.
<?php
Class CustomerModel{
private $db;
function __construct($host,$dbname,$user,$pass){
$this->dbhost = $host;
$this->dbname = $dbname;
$this->dbuser = $user;
$this->dbpass = $pass;
}
private function connect(){
if (!$this->db instanceof PDO){
$this->db = new PDO('mysql:dbname='.$this->dbname.';host='.$this->dbhost, $this->dbuser, $this->dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}
}
public function select_all_customer($cols="*"){
$this->connect();
$sql = "SELECT $cols FROM customer";
$statement = $this->db->prepare($sql);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
public function select_customer($cols="*",$where=null, $id=null){
$this->connect();
$sql = "SELECT $cols FROM customer WHERE $where = :id";
$statement = $this->db->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
}
?>
Now you can access the model like:
<form method="POST" action="task8.php" id="custinfo" >
Choose name:
<select name="customerID" id="customerID">
<option value="0">Choose</option>
<?php foreach($customer->select_all_customer("customerID, lastName") as $row): ?>
<option value="<?php echo $row['customerID']?>"><?php echo $row['lastName']?></option>
<?php endforeach; ?>
</select>
<p><input type="submit" name="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</form>
<?php
//Get customer from form values
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['customerID'])){
$result = $customer->select_customer("*", "customerID", $_POST['customerID']);
//Do something with result
echo '<pre>'.print_r($result, true).'</pre>';
}
?>
Hope it helps

Categories