So here I come with another problem. I can't push strings into mysql table. If I use numbers it works fine. If I try to insert text as value it works as well. No luck with text that was put in textboxes in html.
$current_user = wp_get_current_user();
$hostname = "XXX";
$username = "XXX";
$password = "XXX";
$dbname= "XXX";
$connect=mysqli_connect($hostname, $username, $password, $dbname);
$sql="insert into wypozyczenia (czy_wypozyczony, sn, model) values (2,"
.mysql_escape_string($_POST['SN']).",
".mysql_escape_string($_POST['model']).")";
if ($current_user->ID=2)
{
?><form name="form" method="post" >
Model:</br>
<input type="text" name="model"></br>
Numer Seryjny</br>
<input type="text" name="SN"></br>
<input type="submit" name="button1" value="Send">
</form>
<?php
if(isset($_POST["button1"])){
$model=$_Post["model"];
$SN=$_Post["SN"];
?> <pre><?php var_dump($_POST); ?></pre><?php
mysqli_query($connect,$sql);}}
Try adding single quote before the double quote, like the following:
$sql = "insert into wypozyczenia (czy_wypozyczony, sn, model) values (2,
'".mysql_escape_string($_POST['SN'])."',
'".mysql_escape_string($_POST['model'])."')";
You can use sprintf for beauty code or learning prepare statement in PHP PDO
$sql = sprintf("insert into wypozyczenia (czy_wypozyczony, sn, model) values (2,'%s','%s')"
,mysql_escape_string($_POST['SN'])
,mysql_escape_string($_POST['model']));
Related
i had write a html file which will request some information from user and send it to another php file. The php file will establish the connection to database and insert the value to database. My database name = testdbtable name = table1 I had do some testing on both file by calling an alert message, the alert messages was able to display in the html file,it's seen like the request from the html file cant send to the php file,so the code for inserting data to database can't execute
My Html form as show below
<form id="firstPrize" method="POST" action="firstPrize.php">
<label> Number 1</label>
<input type="text" name="num1"><br>
<label> Number 2</label>
<input type="text" name="num2"><br>
<label> Number 3</label>
<input type="text" name="num3"><br>
<label> Number 4</label>
<input type="text" name="num4"><br><br><Br>
<input type="button" value="enter" name="btnSubmit" onclick="show()">
</form>
firstPrize.php sample code
<?php
$host = "localhost";
$user = "root";
$password = "";
mysql_connect($host,$user,$password);
mysql_select_db("testdb") or die(mysql_error());
Session_Start();
echo("yeah");
if(isset($_POST["btnSubmit"]))
{
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];
$num3 = $_POST["num3"];
$num4 = $_POST["num4"];
mysql_query("insert into table1(num1,num2,num3,num4) values ('num1','num2','num3','num4')");
?>
First, your query can produce SQL Injection. Use Mysqli Prepared Statement :
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["btnSubmit"]))
{
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];
$num3 = $_POST["num3"];
$num4 = $_POST["num4"];
// prepare and bind
$query = $conn->prepare("INSERT INTO table1 (num1, num2, num3, num4) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $num1, $num2, $num3, $num4);
}
This function binds the parameters to the SQL query and tells the database what the parameters are. The "ssss" argument lists the types of data that the parameters are. The s character tells mysql that the parameter is a string.
The argument may be one of four types:
i - integer
d - double
s - string
Second, your if statement misses a closing bracket }
Third, your variable $num1 is never used. You use num1, num2, but you miss the '$'
First, your if statement is missing a closing }.
Second, your SQL query is not inserting the variables you've set above. You've got variables like $num1, but then you are inserting the value just 'num' in your SQL insert. You have to change 'num1', 'num2'... to '$num1', '$num2'...
Third, please do some research on PHP Data Objects (PDO) or MYSQLi (reference links at bottom of post). mysql_ is deprecated and completely vulnerable to malicious injection.
Edit: In addition, please see fred -ii-'s comments below for some sound advice on better INSERT queries. It's safe practice to verify that the values are of the type you're expecting prior to running them against your database.
fred -ii- says:
What if one of those values happens to contain an injection such as '123?
[Use]... (int)$_POST["num1"] and check to see firsthand if the input entered is an integer. There are a few functions that will do that.
Use error reporting and error checking against your query during testing and assuming that you are able to use the MySQL_ API.
References:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/function.mysql-error.php
Otherwise, you will need to resort to either using the MySQLi_ or PDO API.
References:
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/book.pdo.php
.Change your query to;
mysql_query("insert into table1(`num1`,`num2`,`num3`,`num4`) values ('".$num1."','".$num2."','".$num3."','".$num4."')");
followed by the closing bracket ( } ) for your if statement.
<?php
session_start();
// always start your session before any other code
$host = "localhost";
$user = "root";
$password = "";
mysql_connect($host,$user,$password);
mysql_select_db("testdb") or die(mysql_error());
if(isset($_POST["btnSubmit"]))
{
$num1 = mysql_real_escape_string($_POST["num1"]);
$num2 = mysql_real_escape_string($_POST["num2"]);
$num3 = mysql_real_escape_string($_POST["num3"]);
$num4 = mysql_real_escape_string($_POST["num4"]);
// mysql isn't the safest way to put your code out, however if you do, escape it. You may be better off by using prepared statements, but thats up to you, i am just fixing this code
mysql_query("insert into table1(num1,num2,num3,num4)
values ('$num1','$num2','$num3','$num4')");
}
?>
I made a few tweaks in your code and this should do it. Note my additional comments in the code, including the propper escaping your variables, because of the injection danger. Its not my place to judge you on your code, but you would be better off by using prepared statements.
This is a very good topic on this here on stack, I suggest you read it: How can I prevent SQL injection in PHP?
As you clearly mentioned in your question,
" I had do some testing on both file by calling an alert message, the
alert messages was able to display in the html file, it's seen like the
request from the html file cant send to the php file ,so the code for inserting data to database can't execute ~#Heart Break KID "
For That,
1) Change
<input type="button" value="enter" name="btnSubmit" onclick="show()">
To
<input type="submit" value="enter" name="btnSubmit" onclick="show()">
here, type='submit' is required to submit form data..
2) Closing curly brackets are not available. Close if condition.
if(isset($_POST["btnSubmit"]))
{
// Your query.
}
Now, data will go to next page. But, read this question How can I prevent SQL-injection in PHP?
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
UPDATED CODE (using mysqli)
Html form
<form id="firstPrize" method="POST" action="firstPrize.php">
<label> Number 1</label>
<input type="text" name="num1"><br>
<label> Number 2</label>
<input type="text" name="num2"><br>
<label> Number 3</label>
<input type="text" name="num3"><br>
<label> Number 4</label>
<input type="text" name="num4"><br><br><Br>
<input type="submit" value="enter" name="btnSubmit" onclick="show()">
</form>
firstPrize.php
<?php
$host = "localhost";
$user = "root";
$password = "";
$connect = mysqli_connect($host, $user, $password, "testdb");
session_start();
if(isset($_POST["btnSubmit"]))
{
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];
$num3 = $_POST["num3"];
$num4 = $_POST["num4"];
$stmt = mysqli_prepare($connect, "INSERT INTO table1(num1,num2,num3,num4) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'ssss', $num1, $num2, $num3, $num4);
$query123 = mysqli_stmt_execute($stmt);
}
?>
When I submit the below it does not error out but it also does not insert the data into the table. I am a beginner in php so have mercy.
<?php
/* include_once 'dbconn.php';*/
include 'menu.php';
error_reporting(0);
?>
<head></head>
<body>
<form action="add_student.php" method="post">
Name:<input type="text" name="name"><br/>
School:<input type="text" name="school"><br/>
PR:<input type="text" name="pr"><br/>
<input type="submit" name="submit">
</form>
<?php
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "root";
$DB_name = "trackmeet";
$MySQLiconn = new MySQLi($DB_host,$DB_user,$DB_pass,$DB_name);
if($MySQLiconn->connect_errno)
{
die("ERROR : -> ".$MySQLiconn->connect_error);
}
if (isset($_POST['submit'])){
$sql = "INSERT INTO student(Student,School,PR) VALUES ('$_POST[name]','$_POST[school]','$_POST[pr])";
mysqli_query($sql,$MySQLiconn);
mysqli_close($MySQLiconn);
}
?>
</body>
</html>
When I look in the database table the record was not inserted.
I found the problem.
mysqli_query($sql,$MySQLiconn);
changed to
$sql = $MySQLiconn->query($sql);
Thanks for the help. Nice to have people out there that are willing to teach people like me.
You have typo missing this in query ' on value $_POST[pr]
original:
$sql = "INSERT INTO student(Student,School,PR) VALUES ('$_POST[name]','$_POST[school]','$_POST[pr])";
mysqli_query($sql,$MySQLiconn);
fixed:
$sql = "INSERT INTO student(Student,School,PR) VALUES ('$_POST[name]','$_POST[school]','$_POST[pr]')";
mysqli_query($sql,$MySQLiconn);
You have the order of your parameters wrong;
mysqli_query($sql,$MySQLiconn);
should be
mysqli_query($MySQLiconn,$sql);
or use the object orientated method if you so wish
$MySQLiconn->query($sql);
I want to insert a phone number to a database.
My problem now is, how to add a + character to the variable and save it to the database?
This is my form :
<form action="proccess.php" method="POST">
<input type="number" name="number">
<button type="submit">Send!</button>
Dnd this is process.php:
<?php
$phone = $_POST['number'];
$save = mysql_query("INSERT INTO phonenumber VALUES('$phone')");
?>
So I want to insert the data to be +111111111 for example.
<?php
$phone = "+" . $_POST['number'];
$save = mysql_query("INSERT INTO phonenumber VALUES('$phone')");
?>
Additionally, consider using the newer mysqli_-functions.
Consider using PDO.
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$phone = '+'.$_POST['number'];
$sql = "INSERT INTO phonenumber (phone) VALUES (:phone)";
$q = $conn->prepare($sql);
$q->execute(array(':phone'=>$phone));
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 1 year ago.
I am new to PHP, and I have been trying to make a small Homework Organiser Application.
The idea is that you can input a Subject and Description and it will be added to a MySQL Database (that's it for now).
I have created a html form:
<form action="insert.php">
<label for="subj">Subject:</label>
<br>
<input type="text" name="subj">
<br>
<label for="desc">Description:</label>
<br>
<input type="text" name="desc">
<br>
<input type="submit" value="Submit" name="submit">
</form>
and some php code:
<?php
$subject = $_POST['subj'];
$description = $_POST['desc'];
$subject = mysql_real_escape_string($subject);
$description = mysql_real_escape_string($description);
$dbhost = ''; //These are filled in actually
$dbuser = ''; //These are filled in actually
$dbpass = ''; //These are filled in actually
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO organiser '.
'(subject,description) '.
'VALUES ('$subject', '$description')';
mysql_select_db(''); //These are filled in actually
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
The problem is that the input from the Subject and Description boxes on the HTML form don't go into the MySQL Database.
However, If I set
'VALUES ('$subject', '$description')';
to
'VALUES ("test", "test")';
it works.
Any help is appreciated!
Thanks!
In addition to the answer already given in regards to missing dots for the concatenate:
Form method defaults to a GET method, if the method is omitted from the form tag.
You are using <form action="insert.php"> which is equivalent to doing
<form action="insert.php" method = "get"> which is not what you want nor required.
Change it to
<form action="insert.php" method="post">
since you are using POST variables.
That is the contributing reason why 'VALUES ("test", "test")'; works and not the other way, since both of these variables $subject - $description, are based on your POST variables:
$subject = $_POST['subj'];
$description = $_POST['desc'];
You can either do
$sql = "INSERT INTO organiser (subject,description) VALUES ('$subject', '$description')";
as stated in a comment.
or
$sql = "INSERT INTO organiser (subject,description) VALUES ('".$subject."', '".$description."')";
Add error reporting to the top of your file(s)
error_reporting(E_ALL);
ini_set('display_errors', 1);
which would have signaled errors found in your code.
http://php.net/manual/en/function.error-reporting.php
Yet, your method is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
Use a mysqli prepared statements method; it's safer.
<?php
$DB_HOST = "xxx"; // replace with your own
$DB_NAME = "xxx";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
die('Connection failed [' . $conn->connect_error . ']');
}
// optional to check for empty fields
// if(isset($_POST['submit']) && !empty($_POST['subj']) && !empty($_POST['desc'])) {
if(isset($_POST['submit'])) {
$subject = stripslashes($_POST['subj']);
$description = stripslashes($_POST['desc']);
$stmt = $conn->prepare("INSERT INTO organiser (`subject`, `description`) VALUES (?, ?)");
$stmt->bind_param('ss', $subject, $description);
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
else{
echo "<h2>Success!</h2>";
}
$stmt->close(); // Statement
$conn->close(); // MySQLi
}
?>
Form: (new)
<form action = "insert.php" method = "post">
<label for="subj">Subject:</label>
<br>
<input type="text" name="subj">
<br>
<label for="desc">Description:</label>
<br>
<input type="text" name="desc">
<br>
<input type="submit" value="Submit" name="submit">
</form>
Your problem is because you are using single quotes in your $sql declaration,
$sql = 'INSERT INTO organiser '.'(subject,description) '.'VALUES ('$subject', '$description')';
When you use single quotes you are telling PHP that you would like everything within the quotes to be taken literally.
$age = 20;
$myAge = 'I am $age years';
echo $myAge;
This would echo I am $age years since you used single quotes.
However, if you used double quotes instead,
$age = 20;
$myAge = "I am $age years";
echo $myAge;
The output would be,
I am 20 years
Thus, your $sql statement should be (I write it on one line instead),
$sql = "INSERT INTO organiser (subject,description) VALUES ('$subject', '$description')";
^ ^
If you echo your $sql it would become something along the lines of,
INSERT INTO organiser (subject,description) VALUES ('Your subject', 'Your description')
Your use of single quotes within your SQL-statement is correct, you can read more about the subject here: When to use single quotes, double quotes and backticks
You forgot the dots around the variables and you can add some double quotes around that depending on the content of your variables :)
'VALUES ("'.$subject.'", "'.$description.'")';
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'))");