I have code
<form action="insert1.php" form method="POST">
<input type="text" name="product" /></p>
<input type="submit" value="Add">
And
$mysqli = configuration();
$product = $_REQUEST['$product'];
$sql = "INSERT INTO Odiet (product) VALUES ('$product')";
if($mysqli ->query($sql)===TRUE){echo "ok";}
else{echo "not ok";}
$mysqli ->close();
It adds empty string without text.
Please help.
Thanks.
Replace this string:
$product = $_REQUEST['$product'];
With this
$product = $_REQUEST['product'];
You should know which one to use, $_REQUEST opens up a huge security risk to your database. Also use preprared statements.
$sql = "INSERT INTO Odiet (product) VALUES (?)";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("s", $_POST['product']);
if($stmt->execute()){
echo "ok";
} else {
echo "not ok";
}
}
There is also little use in closing the db connection as this is automatically done after script execution.
I just fix one error in you code and you need to put it like this:
$mysqli = configuration();
$product = $_REQUEST['product'];
$sql = "INSERT INTO Odiet (product) VALUES ('$product')";
if($mysqli ->query($sql)===TRUE){echo "ok";}
else{echo "not ok";}
$mysqli ->close();
You get values from html form by field name, but without dolar sign before.
And be aware that your code is not safe. Don't put raw user data in your sql statement, use prepared statements instead
Related
I got a little form:
<form id="plannerform" action="save.php" method="post">
<input id="plannername" placeholder=" " type="text" autocomplete="off" name="plannername">
<input id="plannersubmit" type="submit" value="eintragen">
</form>
As you can see there is the action="save.php" and method="post" on the text-input there is name="plannername".
And thats my php:
$con = mysql_connect("myHost","myUser","myPW");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myDB", $con);
$sql="INSERT INTO anmeldungen (FR_PM)
VALUES ('$_POST[plannername]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
The FR_PM is one column of my table. But when I press submit, not even a new row gets created. Nothing happens.
But when I call my php with "mywebsite.com/save.php" it adds a new row in my table (with no value at "FR_PM", what's pretty obvious)
What do I do wrong?
one of the things that you need to learn if you are a beginner, you should try by all means to stay away from using mysql_* function this is depreciated and its no longer supported in php. instead use mysqli_* with prepared statements, or use PDO prepared statements.
prepared statments make you code looks clean and its easy to debug.
this is you example with prepared statements.
<form id="plannerform" action="save.php" method="post">
<input id="plannername" placeholder=" " type="text" autocomplete="off" name="plannername">
<input id="plannersubmit" type="submit" value="eintragen" name="submit">
</form>
save.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit'])) {
if (empty($_POST['plannername'])) {
die("Enter plannername");
} else {
// prepare and bind
$stmt = $conn->prepare("INSERT INTO anmeldungen (FR_PM) VALUES (?)");
$stmt->bind_param("s", $_POST['plannername']);
if ($stmt->execute()) {
echo "New records created successfully";
} else {
echo "Could not insert record";
}
$stmt->close();
}
}
?>
The reason I used prepared statements :
Prepared statements reduces parsing time as the preparation on the
query is done only once (although the statement is executed multiple
times)
Bound parameters minimize bandwidth to the server as you need send
only the parameters each time, and not the whole query
Prepared statements are very useful against SQL injections, because
parameter values, which are transmitted later using a different
protocol, need not be correctly escaped. If the original statement
template is not derived from external input, SQL injection cannot
occur.
But when I call my php with "mywebsite.com/save.php" it adds a new row
in my table (with no value at "FR_PM", what's pretty obvious)
What do I do wrong?
Well do prevent that from happening you need to check if the form was submitted before you can actual process any thing.
Note: If we want to insert any data from external sources (like user input from a form ), it is very important that the data is sanitized
and validated. always treat input from a form as if its from a very
dangerous hacker
change your insert query:
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('".$_POST["plannername"]."')";
Or
$plannername = $_POST["plannername"];
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('".$plannername."')";
Also, use "name"= and not "id"= in the HTML form.
This is usually misleading when working with forms and HTTP POST method.
you may try
$value = $_POST['plannername'];
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('{$value}')";
I've got the code to insert correctly, but am failing to get it to give me a success message. It always returns failed to add the device to the database, but then I go check the database and it is in fact successfull. Any ideas?
<?php
// Start or resume the session
session_start();
//Check to ensure the user is authorized to view this page
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
// Include Header
include("includes/header.php");
echo "
<div class='form_description'>
<h2>French Lick Resort</h2>
<p>STATUS - Add Ingenico Device to Inventory</p>
</div>
<form id='update' class='fieldset' method='post' action=''>";
$serial=$_POST['serial'];
$model=$_POST['model'];
$deviceCondition=$_POST['deviceCondition'];
$sealCondition=$_POST['sealCondition'];
$location=$_POST['location'];
$deployDate=$_POST['deployDate'];
$weight=$_POST['weight'];
$notes=$_POST['notes'];
//NEW PDO connection
try{
$conn = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);
$sql = "INSERT INTO web01dev4s2.ingenicoInfo (serial, model, deviceCondition, sealCondition, location, deployDate, weight, notes) VALUES ('".$serial."', '".$model."', '".$deviceCondition."', '".$sealCondition."', '".$location."', '".$deployDate."', '".$weight."', '".$notes."')";
$q = $conn->prepare($sql);
$result_1=mysql_query($sql);
$q->execute();
}
catch (PDOEException $pe) {
die("Could not connect to the database" . $pe->getMessage());
}
//End pdo connection
// Display "GO" or "NO GO"
if($result_1){
echo "Device successfully added to the database.";
header( "refresh:2;url=devicelist.php" );
}
else {
echo "Failed to add the device to the database. Please ensure that the device is not already in the database and that all fields are filled out. Notes should be NA if there are no notes to add. Also, ensure the name does not containt any special characters such as quotes.<br />";
Echo "<a href=create.php>Back</a>" ;
}
}
else {
header('Location:login.php');
}
echo "
</form>
</div>
</body>
</html>";
?>
You are mixing your use of PDO and the mysql extension. Don't do that.
If you are going to use PDO, use the prepare statements correctly, as well. You should not put your variables into the raw SQL string, instead use '?' where you expect a value to be inserted. Then pass an array of variables into the statement's execute. This is the PDO way, and it will help prevent SQL injections against your code.
$sql = "INSERT INTO web01dev4s2.ingenicoInfo (serial, model, deviceCondition, sealCondition, location, deployDate, weight, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
$q = $conn->prepare($sql);
// This line should fix your problem
$result_1 = $q->execute(array($serial, $model, $deviceCondition, $sealCondition, $location, $deployDate, $weight, $notes));
I'm having trouble getting a practice signup form to submit data to my database ...
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$name = $email = $password = "";
?>
<form method="post">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Password: <input type="text" name="password">
<br><br>
<input type="submit" value="Submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
function fix_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
In addition to Ugur's answer, you are mismatching mysqli commands and mysql commands. Here's how to do this in an object oriented fashion:
// create mysqli database object
$mysqli = new mysqli_connect("localhost","username","password","database");
// store your query in a variable. question marks are filled by variables
$sql = "INSERT INTO table_name ('username','password') VALUES (?,?)";
// prepare command uses $sql variable as query
$stmt = mysqli->prepare($sql);
// "ss" means your 2 variables are strings, then you pass your two variables.
$stmt->bind_param("ss",$name,md5($password));
// execute does as it seems, executes the query.
$stmt->execute();
// then print your success message here.
Using prepared statements removes the need to sanitize user input, as harmful input is not substituted into the query directly. For more reading:
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
There are some good tips for using prepared statements in many different scenarios, as well as towards the bottom, there is an explanation on how prepared statements prevent SQL injection.
Missing table name
mysql_query("INSERT INTO ...... ('username','password') VALUES ('$name', md5('$password'))");
You're mixing mysql_* with mysqli_* functions, i.e.: mysqli_connect and mysql_query and you're wrapping your column names in quotes, plus you're missing the table name to insert into.
Try the following, fixed code:
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysqli_query("INSERT INTO `your_table` (`username`,`password`) VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
You're also using password storage technology that dates back to 1996. MD5 is no longer considered safe to use.
I suggest you look into PHP's password function: http://php.net/password
And if you're having problems with your fix_input() function, you should consider using the mysqli_real_escape_string() function.
then setting up a DB connection while passing a variable to it.
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
and instead of using:
$name = fix_input($_POST["name"]);
use the following:
$name= mysqli_real_escape_string($db, $_POST['name']);
and do the same for the rest.
you don't have table name in your query! also do not use quotation in your column name :)
you have mixed up mysqli and mysql.
Change
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
to
mysqli_query("INSERT INTO yoour_table(username',password) VALUES ('$name', md5('$password'))");
I'm using php and a database to add books to a database.
HTML
<form method="POST" action="addbook.php">
<p>Enter Book title :<input type="text" name="bookname"></p>
<p>Enter Book Author :<input type="text" name="bookauthor"></p>
<p><input type="submit" value="addbook"></p>
</form>
PHP
$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbcon = mysqli_connect('localhost','root','password','bookstore') or die('asd');
$dbquery = "INSERT INTO books (title,author) VALUES ($bname,$bauthor)";
mysqli_query($dbcon,$dbquery) or die('not queryed');
echo "Your book has been added to your online library";
I'm getting the reply ' not queryed'
try putting single quotes around the values
ie
$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";
You should be using PDO and prepared statements in order to prevent SQL injection. The resultant PHP would be something like this:
$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); //Fill in these variables with the correct values ('localhost' for host, for example)
$st = $dbh->prepare("INSERT INTO books (title,author) VALUES (?,?)");
$data = array($bname, $bauthor);
$st->execute($data);
You can then add logic to check if the statement executed successfully.
Also, I think you just gave us your root password?
For more information about PDO, see this tutorial.
Check the Column names in the table,whether they match with the one in the query.also check whether they are varchar itself.
I dont find any problem in the query, and also try putting
or die(mysqli_error());
and tell what exactly you can see.
If the type is varchar , you have to use single quotes around the values.
$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";
How would I go about writing a SQL statement that would insert values that might contain an apostrophe (for example one person's last name was Conner and another's was O'Conner)? After some searching, I found examples using a double apostrophe (O''Conner example) but each example had the string hard coded in the the INSERT. I haven't run across any examples where the value may or may not contain an apostrophe.
My simple statement doesn't have any issues when no apostrophe is used but when one is it fails. I know I could replace the apostrophe using str_replace but, obviously, that would cause the O'Conner example to be displayed as OConner.
Here is a shorthand version, just for an example:
page1.php
// PHP
include_once('phpdata.php');
if (isset($_POST['firstname']) && isset($_POST['lastname'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
// SQL connection
$insert = doInsert($firstname, $lastname);
// Execute statement using odbc_exec, etc.
}
// HTML
<input type="text" class="required" name="firstname" id="firstname" />
<input type="text" class="required" name="lastname" id="lastname" />
phpdata.php
function doInsert($firstname, $lastname) {
$insert = "INSERT INTO mytable (firstname, lastname)
VALUES ('$firstname', '$lastname')";
return $insert;
}
Using PDO with prepared statements will take care of escaping your inputs :
$dsn = "mysql:host=localhost;dbname=your_db_name";
try {
$db = new PDO($dsn, 'your_username', 'your_pass');
} catch (PDOException $e) {
die( "Erreur ! : " . $e->getMessage() );
}
$query = "INSERT INTO mytable (firstname, lastname)
VALUES (:firstname', :lastname)";
$stmt = $db->prepare($query);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->execute();
Doc : PHP Data Objects
You could use replace to replace all ' with ''. However, the proper way to do it is use parameterized queries where you pass your value to insert to the SQL Statement as a parameter. Then the language can clean up ' and any other characters/keywords that could cause an issue. No matter the language, parameterized queries are the way to go.
Consider using prepared statements. It's the best way to input user submitted data into a database. It makes sure the data is properly escaped automatically!
phpdata.php
<?php
function doInsert($firstname, $lastname) {
$insert = "INSERT INTO mytable (firstname, lastname)
VALUES (?, ?)";
$pstmt = odbc_prepare($odb_con, $insert); /* Use global $odb_con to access the connection */
$res = odbc_execute($pstmt, array($firstname, $lastname));
return $res; /* Should return TRUE on success. */
}
?>
Do note that I haven't included any error checking in my code. Might be wise to implement that as well.
Good luck!
You can try use function addslashes for prepare data before insert.
I don't know how your work with database but this function is simple way for ask to your question.
AddSlashes