I have a simple Form along side a PHP update query that simply isn't working! I know the PHP is working on the page as there are several validation checks that need to be passed before hand which are working perfectly. The form its self is inside the Colorbox Popup tool.
My HTML Form Code is:
<div id="stylized" class="myform">
<form action="#" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_id; ?>" />
<label>First Name:<span class="small">Enter your forename</span></label>
<input id="first_name" type="text" name="first_name" maxlength="50" placeholder="e.g. Joe" required autofocus/>
<div class="spacer"></div>
<input type="submit" id="update" name="update" value="Continue to Step 2!">
</form>
</div>
With the PHP Code as follows (this is above the HTML code on the page):
<?php
if($_POST['update']){
$user_i = $_POST['user_id'];
$f_name = $_POST['first_name'];
$first_name = ucfirst($f_name);
mysql_query("UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'") or die(mysql_error());
} ?>
The actual submit appears to be working, with the Popup refreshing afterwards, but the database does not update! I have triple checked the syntax and the database fields. 'user' and 'first_name' and 'user_id' is correct.
Update: Because the popup box refreshes, I cannot view the error's from the 'or die(mysql_error()) unfortunately, other wise i might have been one step closer.
Any help would be hugely appreciated.
Many thanks in advance.
When you say pop-up box, I assume you are using ajax to communicate from the form to the server, which as you stated is difficult to view submitted data. If this is the case try:
error_log(serialize($_POST));
This will force an entry in your error log with the $_POST data in serialized format, so you can check the values you are submitting are populated correctly.
You will also want to sanitize the variables you are adding to the SQL:
$sql = "UPDATE user SET first_name = " . mysql_real_escape_string($first_name) . " WHERE user_id = " . mysql_real_escape_string($user_i) . " LIMIT 1";
mysql_query($sql);
I would:
print_r($_POST); to view the POST data.
Generate the SQL from a string so it can be printed for debugging purposes, like so:
$sql = "UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'";
echo $sql;
mysql_query($sql) or die(mysql_error());
One of these techniques will likely tell you why the PHP-generated SQL doesn't update your database record.
you set your user_id field by echo $user_id; but your variable name is set to $user_i = $_POST['user_id'];
therefore your user id field is not set and your Mysql command will fail.
Related
I am currently working on a form that uses PHP and SQL to update information in a database. It is functioning properly and updating the information but the issue is... is that it updates everything, including fields that I didn't even put any input in which means it will only update a particular row in the database and leave the others blanks... I need it to just change information from a field with an actual input and leave it if there is no input.
Here is the PHP and SQL code:
try {
$deleteRecId = $_GET['id'];
$update_event_name = $_POST['updateName'];
$update_event_location = $_POST['updateLocation'];
$update_event_date = $_POST['updateDate'];
include 'connect.php';
if(isset($_POST["submit"])) {
// new data
$sql = "UPDATE events SET event_name='$update_event_name',
event_location='$update_event_location', event_date='$update_event_date'
WHERE event_id=$deleteRecId";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
and here if the form:
<form class="update-form" action="<?php echo $_PHP_SELF ?>" method="post">
<p id="input-headers">Event Name</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateName" value="">
</p>
<p id="input-headers">Event Location</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateLocation" value="">
</p>
<p id="input-headers">Event Date</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateDate" value="" placeholder="01/01/2000">
</p>
<input type="submit" name="submit" value="Submit" id="updateBtn">
</form>
So to sum up I need this application to only update information of a field with an actual input and if the form field has no input I need that database info to remain the same. I appreciate any help with this as I am pretty new to these concepts... thanks!
I found a really handy solution to this! Here is how I implemented it into my code.
$sql = "UPDATE events SET event_name=IF(LENGTH('$update_event_name')=0, event_name, '$update_event_name'), event_location=IF(LENGTH('$update_event_location')=0, event_location, '$update_event_location'), event_date=IF(LENGTH('$update_event_date')=0, event_date, '$update_event_date') WHERE event_id=$deleteRecId";
It basically just checks whether the string is empty or not. If it's empty it won't be updated. If it isn't empty it'll go through with the update! Very simple way to achieve this effect when creating an update form.
Using your current code structure, you can do this.
Use SQL to select * from event ID. Populate your update_event_xxx with the parameters.
If $_POST[xx] is blank, ignore. Else, update_event_xx = $_POST[xx]
I have a created an HTML form where users sign up and input there data into an SQL database. I have then retrieved that data in a webpage where they can view their profile. I have created a page where users can edit there profile by creating a form which updates the value in the SQL database for there user id.
I would like the form to use the current value of the SQL cell as the default for that user to make alterations easier. Example: currently user 7 has their city set as New York, when they visits the edit info page, the city field in the form already hase New York as the default value.
I have no problem getting the SQL info and assigning it to a variable, I just don't understand how to set it as the default value. I am aware of how you set default values for input fields though.
My code:
<?php
$id = $_SESSION["user_id"];
// Create a query for the database
$query = "SELECT full_name FROM users WHERE id = $id LIMIT 1";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response){
while($row = mysqli_fetch_array($response)){
echo $row['full_name'];
echo mysqli_error();
}
}
?>
<input type="text" name="aboutme" defualt="<?php echo $row['aboutme'] ?>" >
There's no default value for html input.
Input can has value, using attribute value:
<input type="text" name="some_name" value="Some value" />
In your case it's
<input type="text" name="aboutme" value="<?php echo $row['aboutme']?> />
Input can also has placeholder - some value that is present in an input, but erased when user starts to edit input's content:
<input type="text" name="aboutme" value="<?php echo $row['aboutme']?> placeholder="some value" />
How about
<?php
$id = $_SESSION["user_id"];
// Create a query for the database
$query = "SELECT full_name FROM users WHERE id = $id LIMIT 1";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response){
while($row = mysqli_fetch_array($response)){
echo $row['full_name'];
?>
<input type="text" name="aboutme" value="<?php echo $row['aboutme'] ?>" >
<?php
echo mysqli_error();
}
}
?>
And here is a good example http://www.w3schools.com/php/showphpfile.asp?filename=demo_db_select_pdo
Neither of the answers worked and upon further research and trial and error I created a solution.
I changed the value that was store in the array to just be a normal php variable:
$aboutme = $row['aboutme'];
I then called that variable using the following code:
<input type="text" name="aboutme" value="<?php echo htmlspecialchars($aboutme); ?>" >
Thanks for your help.
I hope you find my answer useful.
Why don't you try using it as a place holder? This will provide editable text.
<input type="text" name="aboutme" placeholder="<?php echo $row['aboutme'];" />
( Just a fun little experiment for my first website )
So this part works fine, it receives the information that is inputted from the form on another page. It adds to the "user" table in which consists of 'user', 'pass' (which are added from this given php code) and also 'ID' which auto increments upon adding to the table and then
'screen_name' and 'email' which I want to further add to the given table via another form.
<?
session_start();
include('dbconn.php');
$username = $_POST['user'];
$password = $_POST['pass'];
$sql = "INSERT INTO `user`(`user`, `pass`) VALUES ('".$username."','".$password."')";
$run = mysql_query($sql);
if($run){
$_SESSION['username'] = $username;
}
?>
This part of the code asks for an email address and a screen name which will be then further stored within the database, however I would like it to add to the specific user's information. As 'user' and 'pass' are already saved, the idea is to further then add 'screen_name' and 'email' to that specific user. Not sure what i've done wrong here. Also each time I refresh the page a blank user is added to a field in the database.
<form id="contact-form" method="post">
<div>
<label>
<span>Userame/Screen Name:</span>
<input placeholder="Please enter your name" name="screen_name" type="text" tabindex="1" required autofocus>
</label>
</div>
<div>
<label>
<span>Email:</span>
<input placeholder="Please enter your email address" name="email" type="email" tabindex="2" required>
</label>
</div>
<div>
<button name="submit" type="submit" id="contact-submit" data-text="...Sending">Submit</button>
</div>
<input type="hidden" name="user" value="<?php echo $_POST['user']; ?> />
</form>
Here is the code which is connected to the above form, it is on the same page and for some reason I am having trouble getting it to even add to any fields within the database let alone the one that is already active for the new user.
<?php
session_start();
include('dbconn.php');
$screen_name = $_POST['screen_name'];
$email = $_POST['email'];
$sql = "UPDATE `user` SET `screen_name` = '$screen_name', `email` = '$email' WHERE user = $username";
$run = mysql_query($sql);
?>
Any help would be more than appreciated. Not usually a guy who asks for help but as being stuck on this problem for ages and looking through multiple Stackoverflow posts, thought I'd add my own question!
It seems that in your second php script you don't initialize $username.
You should probably add $username = $_SESSION['username'];
Also you need to put quotes around it in your query.
About the blank users being inserted on page refresh, my guess would be that the first php script gets executed, but the $_POST variable isn't set.
Finally you should read up on SQL injection http://php.net/manual/en/security.database.sql-injection.php
I am making a php page that retrieves data from a database table and putting it in a table for the user to see via MySQLi commands.
I was wondering how I should approach the reverse situation. I want the user to be able to enter in information into textboxes and the click a button at the bottom of the page called 'save' which will prompt the user "are you sure" before saving to the database. If the user clicks 'yes', then the new entry is inserted into the database.
I have the following code to create the labels and textboxes:
<FORM>
ID: <input type="text" name="id"><br />
NM: <input type="text" name="nm"><br />
Company: <input type="text" name="company"><br />
Address: <input type="text" name="address"><br />
City: <input type="text" name="city"><br />
Zip: <input type="text" name="zip"><br />
State: <input type="text" name="state"><br />
Phone: <input type="text" name="phone"><br />
Website: <input type="text" name="web_site"><br />
</FORM>
However, when it comes to the 'save' button, I can implement the button just fine, but how would I go about saving the information entered into the database?
My initial thought process was to find the values that the user entered. I'm new to PHP and WEB dev in general, but I need to know how to get the value of the text in the textbox. Would I have to sift all the values through via the PHP Post method?
Once I have the information the user wants to enter, I was thinking maybe MySQLi has an insert function, which I found here, http://php.net/manual/en/mysqli.insert-id.php. Then it's just a quick insert and it's in the database after the user gives the 'yes' at the prompt.
Do I have the right idea in mind? Is there a more efficient way to do this?
Any help is greatly appreciated. I've looked around for problems and solutions similar to the ones related to my scenario but there were none. =(
Thanks!
EDIT:
Here is the code I have on the agentprocess.php that the action form sends the information to:
<?php
$agent_nm = $_POST['nm']; // gather all the variables
$company = $_POST['company'];
$address = $_POST['address'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$state = $_POST['state'];
$phone = $_POST['phone'];
$web_site = $_POST['web_site'];
$batch_id = $_POST['batch_id']; // added batch id
//connect
$conn = new mysqli('local', 'admin', 'pass', 'DB');
if(mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
//generate the query (doesn't add id because id is autoincremented)
$query = "INSERT INTO t_agent VALUES (NULL, " . $agent_nm . ", " . $company . ", " . $address . ", " . $city . ", " . $zip . ", " . $state . ", " . $phone . ", " . $web_site . ", " . $batch_id . ")";
//insert and close.
mysqli_query($conn, $query);
mysqli_close($conn);
Despite the code here, I've queried the table and the new entry is not there. Am I missing something here?
Thanks in advance!
Very simple example, added the label tag to the labels for your input and put it inside of a form.
<form method="post" action="process.php" id="myForm" name="myForm" >
<label for="ID">ID</label>: <input type="text" name="ID" /><br />
<label for="nm">NM:</label> <input type="text" name="nm"><br />
<label for="company">Company:</label> <input type="text" name="company"><br />
<label for="address">Address:</label> <input type="text" name="address"><br />
<label for="city">City</label>: <input type="text" name="city"><br />
<label for="zip">Zip</label>: <input type="text" name="zip"><br />
<label for="state">State</label>: <input type="text" name="state"><br />
<label for="phone">Phone</label>: <input type="text" name="phone"><br />
<label for="web_site">Website</label>: <input type="text" name="web_site"><br />
<input type="submit" name="submit" />// this is your submit button
</form>
On the process.php page
//get your inputs from the form
$ID = $_POST['ID'];
//do the same for each of the text inputs
Then you can use mysqli as you described to insert the values into your database, feel free to comment if you need any help with the mysqli part of the question, I didn't include it here since you had the link posted in the original question.
you need to use forms. yes, using the name attributes in your elements, you sift through $_POST(eg. $_POST['company']) for the values you want to store into the DB. here's an example. Use MYSQLi statements instead of mysql as in the eg.
this is simple yet a little complex task for web development beginers.
So I am going to give you an full example of what you need to do...
To do the SAVE button check the fastest way is to use javascript confirm dialog and if confirmed to submit form with javascript also.
The Mysql insert part is easy, you need to check if there is data that you submited via form in $_REQUSET (this works better than $_POST or $_GET because it catchs it both.) and then to connect to db and do an insert query...
Everything is explained in this example:
http://pastebin.com/thNmsXvn
But please use some template engine like Smarty because doing php, javascript and html in one file without template is awful and long term will give you only problems.
I think that I was very clear in the example I put on pastebin but if you have some questions feel free to ask...
Just to add, I have removed ID from HTML form because the best solution for managing ID's in MySQL is auto increment option, you configure that when you create table and set it to a specific field. Most usually it is ID, and it must be an integer.
You should use PDO functions for PHP/MySQL
id field should be autoincrement
<?php
$host= "xxx";
$username="xxx";
$password="xxx";
$database="xxx ";
// Gets data from URL parameters
$name = $_POST['nm'];
//Repeate for all other parameters
// Opens a connection to a MySQL server
try {
// DBH means "DB Handle"
// MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$database", $username, $password);
}
catch(PDOException $e) {
echo $e->getMessage();
}
// STH means "Statement Handle"
$STH = $DBH->prepare("INSERT INTO mytable ( id, nm,company,address,city,zip,state,phone,web_site ) values ( NULL,:nm,:company,:address,:city,:zip,:state,:phone,:web_site)");
$STH->bindParam(':name', $name);
//Repeate for all other parameters
$STH->execute();
//# close the connection
$DBH = null;
?>
I have a small (42 hours) problem with my code trying to edit article
- just the basic editNews.php
When I choose article to edit the data appears in the forms from the DB and when
I hit "update" it returns no error but the data wasn´t updated
<?PHP
connection to database blah blah
?>
<?php
if(isset($_POST['update']))
{
$newsid = $_POST['newsid'];
$date=$_POST['date'];
$time=$_POST['time'];
$location=$_POST['location'];
$result=mysql_query("UPDATE news SET date='$date',time='$time',location='$location', WHERE newsid=$newsid");
header("Location: listNews.php");
}
}
?>
<?php
$newsid = $_GET['newsid'];
$result=mysql_query("select * from news where newsid=$newsid");
while($res=mysql_fetch_array($result))
{
$date = $res['date'];
$time = $res['time'];
$location = $res['location'];
}
?>
This is the form - just the normal one....
<form method="post" action="editNews.php" name="form1">
each item is like
<input type="text" name="headline" value="<?php echo $location;?>" id="UserName">
and
<input type="hidden" name="newsid" value=<?php echo $_GET['newsid'];?>
<input name="update" type="submit" value="update" />
Most likely there is something that I don´t see but "seeing" has taken almost 2 days now
... Is there a possibility I don´t have "edit" privileges in the mySql?
How do you know there was no error? Your code lacks:
print mysql_error();
Add it right after the UPDATE query.
Also your code is most likely to fail whenever the submitted content itself contains single quotes. To send correct SQL to the database it's advisable to apply mysql_real_escape_string() on all input variables.
Try
$result= mysql_query('UPDATE news SET
date = "'. $date .'",
time = "'. $time. '",
location = "' .$location. '"
WHERE newsid = '.$newsid.';') OR die(mysql_error());