When I type something in a text box and save it in mysqli it works perfectly but when I refresh that same page the text that i wrote stuff, it disappears for no reason. I also I have another text box in that page and it works perfectly fine. How can I fix that? The bio text box is the one I'm having issues.
$getpro = mysql_fetch_assoc(mysql_query("SELECT * FROM `profile` WHERE username = '".$user_data['username']."' "));$pro = $getpro;
$bios = $pro["bios"];
$realtionship = $pro["realtionship"];
$impmessage = $pro["impmessage"];
if ($_POST['bio']){
$bio = $_POST['bio'] ;
$query;
}
if ($_POST['impmessage']){
$impmessage = $_POST['impmessage'] ;
$query;
}
$query = mysql_query("UPDATE `profile` SET bios ='$bio', impmessage = '$impmessage' WHERE username = '".$user_data['username']."'");<form name="bio"action="" method="post">
<p>Important Message</p> <textarea cols="50" style="resize:none" name="bio" rows="7" ><? echo $bios; ?></textarea><br />
<input type="submit" value="change">
</form><hr /><form name="impmessage"action="" method="post">
<p>Important Message</p> <textarea cols="50" style="resize:none" name="impmessage" rows="7" ><? echo $impmessage; ?></textarea><br />
<input type="submit" value="change">
</form>
I have rearranged & removed some of the code and tried tidying it a bit:
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) // if form is submitted using POST method
{
if ( isset( $_POST['bio'] ) ){
$bio = mysql_real_escape_string( $_POST['bio'] ); // escape special characters is user input
$query = mysql_query("UPDATE `profile` SET bios ='$bio' WHERE username = '".$user_data['username']."'"); //update bios
}
if (isset( $_POST['impmessage'] ) ){
$impmessage = mysql_real_escape_string( $_POST['impmessage'] ); // escape special characters is user input
$query = mysql_query("UPDATE `profile` SET impmessage = '$impmessage' WHERE username = '".$user_data['username']."'"); //update impmessage
}
}
$pro = mysql_fetch_assoc(mysql_query("SELECT * FROM `profile` WHERE username = '".$user_data['username']."' "));
?>
<form name="bio" action="" method="post">
<p>Bios</p>
<textarea cols="50" style="resize:none" name="bio" id="bio" rows="7" ><?php echo $pro["bios"]; ?></textarea>
<br />
<input type="submit" value="change">
</form>
<hr />
<form name="impmessage" action="" method="post">
<p>Important Message</p>
<textarea cols="50" style="resize:none" name="impmessage" id="impmessage" rows="7" ><?php echo $pro["impmessage"]; ?></textarea>
<br />
<input type="submit" value="change">
</form>
Some notes for you:
First of all avoid mysql_* functions. Instead use mysqli or PDO
I would always prefer writing the code for processing of user inputs in the very beginning of the page, ie. before outputting anything. Because, if the user inputs makes any changes on the output, it would easily display the updates since we are doing the processing before outputting anything. So, when we query the db, it would fetch the updated data. Also, if we wanted to redirect to another page or have to send some other headers to the browser, we could do it, as the headers should always be sent before outputting anything.
Another thing is, always escape user inputs. Otherwise, prone to sql injections. Best thing would be to use prepared statements which is available in mysqli & PDO.
When you name id of elements in your HTML, make sure that it is unique. Because no same ids could occur twice. But class names can occur for any number of times.
Also make sure that your PHP code doesn't get mixed up with the HTML. Properly enclose the PHP code with the <?php & ?> tags. I would always prefer avoiding shorthands.
Since you are using two forms, both the input won't reach the server side. Only a single one. If you wanted to both inputs to be reached at the same time, then use a single form.
I have also avoided unwanted assignment operations from the fetched data, to other variables.
Also, you should always properly indent your code for better readability.
I hope this would help. Wish you good luck. :)
Looks like you're running your update query every page load. If the post value isn't filled and you refresh it's going to update with empty values.
Ps sberry is right lots of other things to fix before this goes production.
Related
i am trying to get text from a text box into my database, but it wont go through. i have tried so many things please help!! the else statement always executes, because I get the message "no submission received on my webpage", which means the first if statement definitely executes.
As FirstOne said you need to name the input "submit".
<input class="input" type="submit" name="submit" value="شارك"/>
Hello There are two problem's with your code ..
First one add name attr in your submit button because you are checking isset($_POST['submit'])
<input class="input" type="submit" name="submit" value="شارك"/>
Second Update Your $query with this
$query= "INSERT INTO hamsasubmissions (secret,popularity) VALUES ('".$_POST["newSecret"]."',0)";
first of all you didn't give the submit button a name so you must name it 'submit' to match what you wrote in your code and also your SQL query seems to be incorrect, here's a snippet with the desired changes:
<form method="post" action="post.php">
<textarea name="newSecret" id="help" class="textarea" rows="20" cols="100">
</textarea>
<input class="input" name="submit" type="submit" value="شارك"/>
</form>
<?php
if(isset($_POST['submit'])) {
// trim possible begining/ending whitespaces from the the textarea value. But you still need to escape it againt SQL injection !
$newSecret = trim($_POST['newSecret']);
if(isset($newSecret)[0]) {
include "db_connect.php";
$query= "INSERT INTO hamsasubmissions (secret,popularity) VALUES ('" . $newSecret . "', 0)";
if(!mysqli_query($mysqli,$query)){
echo "no submission received";}
else{echo "Secret submitted.";}
}
}
?>
I'm creating a php-post form, containing: Who, What, Where, Contact and date_created.
I've made a database with these rows.
Here's my HTML Form code:
<form id="contactform" action="post.php">
<p class="contact"><label for="who">Who</label></p>
<input id="who" name="who" placeholder="Who are you? (First & Second name)" required="" tabindex="1" type="text">
<p class="contact"><label for="email">What</label></p>
<input id="what" name="what" placeholder="What do you want?" required="" type="text">
<p class="contact"><label for="username">Where</label></p>
<input id="where" name="where" placeholder="Country, City, Street..." required="" tabindex="2" type="text">
<p class="contact"><label for="password">Contact</label></p>
<input type="text" id="contact" name="contact" placeholder="Phone number or email"required="">
<br><br>
<input class="buttom" name="submit" id="submit" tabindex="5" value="Submit" type="submit">
And here's the php post.php code:
<?php
// Grab our POSTed form values
// Note that whatever is enclosed by $_POST[""] matches the form input elements
$who = $_POST["who"];
$what = $_POST["what"];
$where = $_POST["where"];
$contact = $_POST["contact"];
// Connect to our DB with mysql_connect(<server>, <username>, <password>)
$sql_connection = mysql_connect("server_name", "admin", "password");
mysql_select_db("database_name", $sql_connection);
$sql = "INSERT INTO content (
who,
what,
where,
contact,
date_created
)
VALUES (
'$who',
'$what',
'$where',
'$contact',
NOW()
)";
mysql_query($sql, $sql_connection);
mysql_close($sql_connection);
?>
When I try to post something, nothing is happening. The screen is just white, the database is empty and the url is like this:
http://my-website.com/post.php?who=Firstname+Secondname&what=Some+sentences+here-and&where=America&contact=some#website.com&submit=Submit%21
Just as HamZa DzCyberDeV said, you didn't specify which method you're using in <form> tag.
For situations when you're POSTing something in your database, just as you are now - use method="post" and for forms when you're searching for something, use method="get".
In case of using post method, your URL will change to only my-website.com/post.php and in case of using get method, your URL will change to something like my-website.com/post.php?... (where your things which you're getting are going) - just how you got URL after submitting.
The screen is just white because post.php (where you're going after clicking on submit button) doesn't contain anything to send to output, which you can easily do with echo.
For instance, you can make a new html page which will be written down with echo:
echo '
<html
<body>
This is my website!
</body>
</html>
';
Also, what you could do is to use include() php script which has already formed HTML, or you can check out here for some other redirect methods:
http://php.about.com/od/learnphp/ht/phpredirection.htm
Just remember that PHP is language which server is processing and only HTML tags (with CSS and JS) are sent to other browser to be read.
For more about POST and GET method you can read here:
http://php.net/manual/en/reserved.variables.post.php
http://php.net/manual/en/reserved.variables.get.php
why don't you try this to get an error or a clue to what is going wrong, enclose your code in try and catch blocks:
try {
// your code
} catch ( Exception $e ) {
echo $e->getMessage();
}
So, I have a page with a bunch of workorders on it. Each workorder is a row in a single table, and gets put on the page with a while() statement.
I'm trying to update each row with a simple form that I put inside the while(), and an UPDATE/WHERE statement to actually add the information to the table.
Instead of adding it to the specific row, it adds it to Every row. The only thing I can think of is that my WHERE condition is wrong, but I can't seem to figure it out. Maybe it just needs fresh eyes, or maybe I'm heading in Completely the wrong direction.
Also, any specific instructions on security, a better way to do it, etc. would be very helpful. I'm learning PHP on the fly and could use a helping hand. :)
<?php
$query = "SELECT * FROM client_information";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$which_ad = $row['ID'];?>
<b>Name:</b> <? echo $row['billing_name']; ?> <br>
<b>Job Type:</b> <? echo $row['job_type']; ?> <br>
<b>Size:</b> <? echo $row['size']; ?> <br>
<b>Text:</b> <? echo $row['text']; ?> <br>
<b>Notes:</b> <? echo $notes; ?> <br>
<br><br>
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="submit" name="submit" value="Submit"></form>
<?
$email_message = htmlspecialchars ("{$_POST['email_message']}", ENT_QUOTES);
if (mysql_errno() != 0) {
die(mysql_error());
}
mysql_query(
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$which_ad'"
);
if (mysql_errno() != 0) {
die(mysql_error());
}
}
?>
You don't specify the id in your form:
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="hidden" name="id" value="<?php echo $which_ad; ?>">
<input type="submit" name="submit" value="Submit">
</form>
you need to also make sure you know what id was submitted:
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$_POST['id']'"
Of course, you're wide open to attacks like this as everyone else is saying. You need to look into mysqli or pdo to sanitize your input...
Ans also upon inspection you're evaluating your post data in the loop. Don't do that. Just do your evaluation before everything else is processed on the page...
<?php
if($_POST)
{
//run processing here
}
// do your fetch code here and display the forms...
I have a form with a hidden field that looks something like this:
<form id="myform" method="post" action="/myphp.php">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" />
</div>
<div>
<input type="hidden" id="id" name="title" value="Bob's Group (test)" />
</div>
<div>
<input type="submit" value="Sign up" class="send_button" />
</div>
</form>
The hidden value 'title' get's its value from a Perch CMS php inline script and in this case it's "Bob's Group (test)".
The php script to process this form looks like this:
<?php
// Get and check input
$title = check_input($_POST['title']);
echo "title: $title<br>";
$name = check_input($_POST['name']);
$title = mysql_real_escape_string($title);
// Some sql queries that use $title
?>
The output looks like this:
title: Bob's Group (test)
title:
In other words, mysql_real_escape_string causes title to become a blank string.
Is there a way to handle this form value and generate a safe sql string to use?
mysql_real_escape_string() is MySQL server-side. It requires an active DB connection. Check if you have one in the moment of check.
Just a note, not an advice: mysql_escape_string() is client-side, i.e. works in PHP even without active MySQL connection.
You have to have an active connection to MySQL for msyql_real_escape_string() to work. You're most likely getting back a boolean FALSE from m_r_e_s() because you haven't connected, and it's issuing an error. If you do
$title = mysql_real_escape_string($title) or die(msyql_error());
^^^^^^^^^^^^^^^^^^^^^^
you'll most likely get a "not connected" error message.
The connection is required so m_r_e_s can properly escape things - it basically asks the server what its must-be-escaped metacharacters are so it can do its job properly.
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.