I just got assignment to make html form with php that will store information in mysql database. It is not making table and I can't figure out why. Here is html code(btw I dont care about sql injection becouse this is just for school)
<?php
#$ime = $_POST['ime'];
#$prezime = $_POST['prezime'];
#$email = $_POST['email'];
#$adresa = $_POST['adresa'];
#$misljenje = $_POST['misljenje'];
$conn = mysqli_connect("localhost","root","");
mysqli_query($conn,"create database baza_podataka");
mysqli_select_db($conn,"baza_podataka");
mysqli_query($conn,"create table 'podatci' (id int primary key auto_increment, ime varchar(10), prezime varchar(10), email varchar(20), adresa varchar(20), misljenje varchar(100))");
mysqli_query($conn,"INSTERT INTO `podatci` VALUES ('$ime','$prezime','$email','$adresa','$misljenje')");
?>
and html
<form name="forma" action="obrada.php" method="post">
<label>Ime :</label>
<input type="text" id="ime" size="20"/><br><br>
<label>Prezime :</label>
<input type="text" id="prezime" size="20"/><br><br>
<label>E-mail :</label>
<input type="text" id="email" size="20"/><br><br>
<label>Adresa :</label>
<input type="text" id="adresa" size="40"/><br><br>
<label>Vase misljenje :</label><br><br>
<textarea name="misljenje" id="misljenje"></textarea>
</label><input type="submit" id="submit" name="submit"/>
You have lot of problems..
Remove the error suppression operator. #$ime = $_POST['ime']; Remove the # from all the variables.
You are creating the database each and every time whenever this script is called. [which is totally wrong]
It is INSERT not INSTERT on your query.
You are passing the $_POST parameters directly onto your query which makes you 100% vulnerable to SQL Injection. Switch to Prepared Statements to overcome this.
First of all I don't see a </form> on your HTML code.
Try using $_REQUEST['htmlvariablename'];
ime = $_REQUEST['ime'];
$prezime = $_REQUEST['prezime'];
$email = $_REQUEST['email'];
$adresa = $_REQUEST['adresa'];
$misljenje = $_REQUEST['misljenje'];
...And as stated earlier you are vulnerable to SQL injection.
1) Use INSERT instead of INSTERT
mysqli_query($conn,"INSERT INTO `podatci` VALUES ('$ime','$prezime','$email','$adresa','$misljenje')");
2) Escape all of your data using mysqli_real_escape_string
3) Never use error suppressor on your code #, instead use isset() to check if it is set or not.
$conn = mysqli_connect("localhost","root","");
$ime = isset($_POST['ime']) : mysqli_real_escape_string($conn, $_POST['ime']) ? '';
$prezime = isset($_POST['prezime']) : mysqli_real_escape_string($conn, $_POST['prezime']) ? '';
$email = isset($_POST['email']) : mysqli_real_escape_string($conn, $_POST['email']) ? '';
$adresa = isset($_POST['adresa']) : mysqli_real_escape_string($conn, $_POST['adresa']) ? '';
$misljenje = isset($_POST['misljenje']) : mysqli_real_escape_string($conn, $_POST['misljenje']) ? '';
4) Finally, there is no need to create the database and/or table every load, you should only do it once.
Related
I created a simple form in PHP so I can add the submitted data to a database. The connection works fine but every time I refresh the form page, it adds a blank Row into the Database. Also, it shows an error message "Undefined index: Fname in C:\xampp\htdocs\projekt\submitform.php on line 38"
Here is the code I've written so far:
<?php include 'config.php'; ?>
<?php
$Fname = isset($_POST['Fname'])?$_POST['Fname']:'';
$Lname = isset($_POST['Lname'])?$_POST['Lname']:'';
$Email = isset($_POST['Email'])?$_POST['Email']:'';
$PhoneNo = isset($_POST['PhoneNo'])?$_POST['PhoneNo']:'';
$query = "INSERT INTO users(Fname,Lname,Email,PhoneNo) VALUES ('$Fname','$Lname','$Email','$PhoneNo')";
$result = mysqli_query($con,$query) or die ("problem inserting data into database");
?>
<p><span class="error">* required field</span></p>
<form action = "" method = "post">
Name: <input type = "text" name = "Fname">
<span class=error>*</span><br>
Surname: <input type="text" name="Lname">
<span class=error>*</span><br>
Email: <input type = "email" name = "Email">
<span class=error>*</span><br>
Phone Number: <input type = "tel" name="PhoneNo"><br>
<input type = "submit" value="submit">
</form>
You should 'listen' for a post request and only then insert the values.
<?php
if(isset($_POST['submit'])) {
$Fname = $_POST['Fname'];
$Lname = $_POST['Lname'];
$Email = $_POST['Email'];
$PhoneNo = $_POST['PhoneNo'];
$query = "INSERT INTO users(Fname,Lname,Email,PhoneNo) VALUES ('$Fname','$Lname','$Email','$PhoneNo')";
$result = mysqli_query($con,$query) or die ("problem inserting data into database");
}
?>
That error you got was telling you there was no post data set.
Please note that directly using the input data for SQL is a huge security risk! You should at least use mysqli and mysqli_real_escape_string($Fname) when storing the input data.
Even more secure would be using PDO and prepared statement.
you need to check if there is POST variables like this:
if (isset($_POST['Fname'])) { //here you can check whatever post values you want to check
$Fname = $_POST['Fname'];
$Lname = $_POST['Lname'];
$Email = $_POST['Email'];
$PhoneNo = $_POST['PhoneNo'];
$query = "INSERT INTO users(Fname,Lname,Email,PhoneNo) VALUES
('$Fname','$Lname','$Email','$PhoneNo')";
$result = mysqli_query($con,$query) or die ("problem inserting data into
database");
}
Because every time you visit the page it try to insert record, but you need to insert record only if there is post values (means that someone as fill the form)
so you need to check if the refresh comes from a form submit
Each time i update the database, it create a new row with the new information i was trying to update and a new customerID each time, is there a way to resolve this.
The update query calls two tables Cus_acct_details and cus_register. The query is meant to change cus_email in both tables, and update all the information in cus_acct_details.
PHP
<?php
//$user = $_SESSION["Cus_Email"];
$Cust_ID = $_SESSION["CustomerID"];
if (isset($_POST['Update'])) {
$UpdateFname = $_POST['fname'];
$UpdateLname = $_POST['Lname'];
$UpdateEmail = $_POST['email'];
$UpdatePhone = $_POST['phone'];
}
$sql = $dbc->query("UPDATE Cus_Register, Cus_acc_details
SET Cus_acc_details.CUS_Fname = ' $UpdateFname',
Cus_acc_details.CUS_Lname = ' $UpdateLname',
Cus_acc_details.CUS_Email = ' $UpdateEmail',
Cus_acc_details.Cus_Phone = ' $UpdatePhone',
Cus_Register.CUS_Email = ' $UpdateEmail',
ON Cus_Register.Cus_Email = Cus_acc_details.Cus_Email
WHERE Cus_Register.CustomerID = '$Cust_ID'
");
print_r($_POST);
header('Location: Cus_Account.php');
?>
HTML
<section class="container">
<form id="myform " class="Form" method="post" action="Cus_Account.php?c_id=<?php echo $c_id ?>" accept-charset="utf-8">
<!-- <div id="first">-->
<input type="text" id="fname" name="fname" value="<?php echo $_SESSION['fname']; ?>" required>
<input type="text" id="lname" name="lname" value="<?php echo $_SESSION['lname']; ?>" required>
<input type="text" id="email" name="email" value="<?php echo $_SESSION['Cus_Email']; ?>" required>
<input type="number" id="phone" name="phone" value="<?php echo $_SESSION['phone']; ?>" required>
<input type="submit" name="Update" value="Update">
<br>
</form>
The $cust_id variable was defined earlier on.
Where have a gone wrong.
An UPDATE statement won't insert a new row. There must be an INSERT statement running. (1)
The syntax of the update statement looks wrong to me, I'd expect that to be throwing an error.
The ON clause is used with the JOIN keyword, but the old-school comma operator is used for the join operation. The SET clause should be the last thing before the WHERE clause.
UPDATE Cus_Register
JOIN Cus_acc_details
ON Cus_Register.Cus_Email = Cus_acc_details.Cus_Email
SET Cus_acc_details.CUS_Fname = ?
, Cus_acc_details.CUS_Lname = ?
, Cus_acc_details.CUS_Email = ?
, Cus_acc_details.Cus_Phone = ?
, Cus_Register.CUS_Email = ?
WHERE Cus_Register.CustomerID = ?
It seems odd that there's an extra space in the string literals.
Assigning the return from a ->query() to a variable is a common pattern. But naming that variable $sql is very strange.
The normative pattern is to assign the SQL text (a string) to a variable named $sql, and then referencing the variable
$sql = 'SELECT foo FROM bar ORDER BY foo LIMIT 1';
$result = $dbc->query($sql);
Then check the return from query, to see if it was successful, or if an error occurred. If you're using PDO, you can configure the connection to throw an exception, and handle it in a catch block.
If your code doesn't do that, it's putting it's pinky finger to the corner of its mouth Dr. Evil style and saying "I'm just going to assume it all goes to plan. What?"
Also, the code appears to be vulnerable to SQL Injection. If any potentially unsafe values are included in the SQL text, those values must be properly escaped before they are included.
The preferred pattern is not even include the values in the SQL text, but to use prepared statements with bind placeholders, and supply the values through the placeholders.
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
(1.) Of course it's possible to define a BEFORE UPDATE and/or an AFTER UPDATE trigger that performs an INSERT. But it's the INSERT statement that inserts the row, even if the firing of the trigger is "caused" by running an UPDATE.
Set CustomerID to be a key and add an ON DUPLIACTE KEY UPDATE clause
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have already checked with htmlentities, htmlspecialchars, mysql_real_escape_string but nothing helped me.
I just want to save "Hello my name is john & my native is chennai"
when i tried to save this, only "Hello my name is john " is saved.
what should i do to store & symbol from php form to mysql database?
Update with sample code:
Let the input field be like,
<input type="text" name="product_desc" />
and getting values in php be like
$product_description = htmlentities($_POST['product_desc']);
$product_description2 = htmlspecialchars($_POST['product_desc']);
Use prepared statements. See reference(s) below.
Here is a script that I use (pulled from one of my libraries) and it works, even with the ampersand (pre-tested) and make sure the column is varchar.
Pre-test entered "John & me" in DB successfully.
You will need to modify it to suit your inputs etc.
-mysqli with prepared statements method
<!doctype html>
<head></head>
<title></title>
<body>
<form action="<?php echo htmlentities($_SERVER["PHP_SELF"]); ?>" method="post">
<p><strong>Name: </strong>
<input name="name" type="text" width="50">
</p>
<p><strong>Email: </strong>
<input name="email" type="text" width="50" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
</body>
</html>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
if( isset($_POST['submit'])
&& !empty($_POST['name'])
&& !empty($_POST['email']) ){
/* ===================== not all parts needed, modify to suit ======================= */
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Not a valid email
$error_msg = '<p class="error">The email address you entered is not valid.</p>';
echo $error_msg;
exit;
}
/* ===================== not really needed, just querying ======================= */
$checkemail = mysqli_real_escape_string($con, $_POST['email']);
$query = "SELECT * FROM yourTable WHERE email = '".$checkemail."'";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
if (mysqli_num_rows($result) > 0) {
echo $checkemail . " already exists in DB";
exit;
}
$name = stripslashes($_POST['name']);
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql = mysqli_prepare($con, "INSERT INTO yourTable
(id, name, email)
VALUES (null,?,?)");
$sql->bind_param("ss", $name, $email);
$sql->execute();
if($sql){
echo "Success!";
}
}
else{
echo "Fill in all fields.";
}
Reference(s):
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
There is nothing special about the & character in a string in php.
The only way you can get the result you get (everything after the & is not stored...), is when you send the data to your php script and you are building the data string manually without encoding it properly.
If you use javascript to make your POST request, you would need to encode your values using encodeURIComponent() before you add them to the query string.
If you use php (cURL for example) to make your POST request, you need urlencode() to correctly encode the value before you add it to the query string.
And to store any string with any kind of characters in a database, the recommended method is to use a prepared statement with bound parameters. However, that does not seem to have anything to do with your problem.
Have you tried using HTML Entities?
& = $
Info about all the Entities:
http://www.w3schools.com/html/html_entities.asp
After writing a whole lot of much more complicated code that works beautifully, THIS is the code that is giving me issues.
Simple form
<form action="res/scripts/editsubscriber.php" method="post">
<label for="name">Name: </label>
<input name="name" type="text" value="<?php echo $name; ?>">
...etc, etc...
</form>
Submits to this script:
include('appvars.php');
if(isset($_POST['submit'])){
$id = $_POST['id'];
$name = $_POST['name'];
$email = $_POST['email'];
$month = $_POST['month'];
$day = $_POST['day'];
$year = $_POST['year'];
$date = $_POST['date'];
$time = substr($date, 0, (stripos($date, " ")+1));
$time = str_replace($time, '', $date);
$created = $year.'-'.$month.'-'.$day.' '.$time;
$query = "UPDATE newslettersubscribers SET name = '$name', email = '$email', created = '$created' WHERE id = $id)";
mysqli_query($dbc, $query);
}
It posts, I've echoed all of the variables, they change just fine, but it still won't update the database. Someone please tell me what i'm missing...
remove extra ) on your update statement
read article to avoid SQL Injection
Best way to prevent SQL injection in PHP?
You got a strange trailing ) in your SQL query. Have you executed it in a SQL client ?
Do you have an ID form input?
<input name="id" type="text" value="<?php echo $id; ?>">
Also, you're not escaping sql/html.
This code will compromise your database's security severely. Since none of the parameters are sanitized before being included in the query, anyone with basic security knowledge can take over your application in seconds.
To address the security issues and your bug, you may want to look into
http://php.net/manual/en/pdo.prepared-statements.php
I have a question, I am new to PHP and I have been working on some exercises. The one I am currently working on is to create a simple form that will search a database (first name, last name). The returned results should then be populated into another form. This way, if I want to update the record, all I have to do is change the value of the populated form and hit Update. I have create the database no problem.
The following is the code. (Please don't laugh, I'm very new...I am sure there are much more efficient ways of doing this, but I'm just playing around right now)
Here is the form:
<form action="" method="post">
<strong>Search for name</strong><br>
<label for="fname">First Name</label>
<input type="text" name="fname">
<label for="lname">Last Name</label>
<input type="text" name="lname">
<input type="submit" name="submit" value="Search">
</form>
And here is the PHP:
if( isset( $_POST['submit'] ) ){
$first_name = $_POST['fname'];
$last_name = $_POST['lname'];
if ( $first_name == NULL || $last_name == NULL ) {
echo "please enter search record";
}
else {
$query = "SELECT first_name, last_name FROM formdata WHERE first_name LIKE '%$first_name%' OR last_name LIKE '%$last_name%'";
$result = mysqli_query( $conn, $query );
$result_array = mysqli_fetch_row( $result );
$fname_value = $result_array[0];
$lname_value = $result_array[1];
echo "
<form action='' method='post'>\n
<label for='fname_u'>First Name</label>\n
<input type='text' name='fname_u' value='$fname_value'>\n
<label for='lname_u'>Last Name</label>\n
<input type='text' name='lname_u' value='$lname_value'>\n
<input type='submit' name='update' value='Update'>\n
</form>";
}
}
if( isset( $_POST['update'] ) ) {
$first_name_u = ( $_POST['fname_u'] );
$last_name_u = ( $_POST['lname_u'] );
$query_update = "UPDATE formdata SET first_name = '$first_name_u', last_name = '$last_name_u' WHERE first_name = '$fname_value';";
echo $query_update; // this is just for testing
}
This code seems to work and do what I want, all the way up to when I submit the updated information. I can't figure out how to carry over the value of the $fname_value variable to the if( isset( $_POST['update'] ) ) conditional. I am thinking I can't because they are two different POSTS? I really don't know...I just need to find a way to get value of the retrieved form data and use for the WHERE clause.
Again, I'm very new and just getting my feet wet with this kind of stuff ... Any help would be great
Thanks
I think you have a typo in your code. Your POST data is saved to the variable $first_name, but when you query SQL you are using $first_name_r instead of $first_name.
I'm thinking the typo is the answer, but I have to point out one deadly mistake you've made, and that is that you're piping user-supplied input directly into an SQL query. This opens your code to a slew of malicious attacks called SQL injection attacks. I'm not trying to be preachy, but it's very important that you read and understand that article, especially the part about Mitigation at the bottom.
I would suggest you use something like this instead:
$query = 'SELECT first_name, last_name '.
'FROM formdata WHERE first_name LIKE ? OR last_name LIKE ?;';
$sth = mysqli_prepare($dbh, $query);
mysqli_stmt_bind_param($sth, "s", '%'.$first_name.'%');
mysqli_stmt_bind_param($sth, "s", '%'.$last_name.'%');
$result = mysqli_execute($sth);
I know it's a bit longer and more complicated, but trust me, it will save you a world of headache. The sooner you learn about this and get it deeply ingrained in your psyche that you can never, ever, ever write a query that passes unsanitized input straight to the database, the happier we all will be (and the longer you will get to keep your job eventually. ;).
Sorry if I'm coming on strong, but in my opinion, the single most important lesson you need to pick up early in developing database-driven web sites is that you really need to be proficient at spotting injection vulnerabilities to the point where it's automatic and when you see it, you think, "Ooh! Noooo! Don't do that!!!"
Above answer found your isssue, but on a sidenote:
$first_name = $_POST['fname'];
$last_name = $_POST['lname'];
Do not do this. That my friend is the most common security vulnerability for php applications.
The most 2 most important things to remember when scripting is
Filter input, and
2: Escape output.
See this write-up for more details ..
In your case, the input values are not filtered, or checked for malicious/improper values.
Here is another primer on this page to see a few tips and how to address filtering.
Keep it up, those exercises are a fine way of picking up chops.
Happy coding friend.
Okay, re-reading your post, I think I see what you're trying to do and where you're having difficulty. Normally, you won't have two separate pages for one identical form like this. Typically, you'll code it more along these lines, and please keep in mind that I'm winging this off the top of my head, not actually testing it, so minor corrections and/or tweakage may be required:
<?php
$fname_value = '';
$lname_value = '';
if (isset($_POST['submit']) && $_POST['submit'] === 'Search') {
if (isset($_POST['fname']) && isset($_POST['lname'])) {
// We are processing a submitted form, not displaying a brand new one
// from scratch. Code any post-validation steps.
// Fetch the user information from the database. You'll need to define
// the $host, $user, $password, and $dbname variables above, or
// substitute literal strings with real information in here.
$dbh = new mysqli($host, $user, $password, $dbname);
$sql = 'SELECT first_name, last_name'.
'FROM formdata WHERE first_name LIKE ? OR last_name LIKE ?;';
$sth = $dbh->prepare($sql); // Use parameters to avoid injection!
$sth->bind_param('s', $_POST['fname']);
$sth->bind_param('s', $_POST['lname']);
if ($sth->execute()) {
$result = $sth->get_result();
if (($row = $result->fetch_assoc()) != NULL) {
// Set the default values displayed in the text edit fields.
$fname_value = $row['first_name'];
$lname_value = $row['last_name'];
}
}
// Whatever other processing you want to do if this is a submitted
// form instead of displaying the page from scratch.
}
}
?>
<html>
<body>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<strong>Search for name</strong><br />
<label for="fname">First Name</label>
<input type="text" name="fname" value="<?= htmlentities($fname_value) ?>">
<label for="lname">Last Name</label>
<input type="text" name="lname" value="<?= htmlentities($lname_value) ?>">
<input type="submit" name="submit" value="Search">
</form>
</body>
</html>