So currently, this is the code I have
index.php:
<form action="insert.php" method="post">
Comments:
<input type="text" name="comment">
<input type="submit">
</form>
insert.php:
<?php
include ('index.php');
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "x", "", "comment_schema");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','$comment')";
// attempt insert query execution
if(mysqli_query($link, $sql)){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
When I do echo $comment, nothing gets printed out. However, if I do something like echo "hi" it works. I think for some reason the $_POST is not being recognized. Any suggestions to make this work or if I'm doing it wrong.
My goal is to take a user input and insert into a database on phpmyadmin. Currently, it is able to insert, however it inserts an empty value. I only have two columns in my database. An ID and a Comment column. The ID is auto incremented. The comment is what I get from the user.
Check Once what is your data type of comment in database.(I prefer Varchar()).
Try this as it is:-
<form action="insert.php" method="POST">
Comments:
<input type="text" name="comment"/>
<input type="submit" name="submit" value="submit">
</form>
<?php
include ('index.php');
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect("localhost", "x", "", "comment_schema");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','$comment')";
if(mysqli_query($link, $sql)){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
try this
<?php
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$link = mysqli_connect($host, $user, $password, $db);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
$sql = "INSERT INTO parentComment(ID, Comment) VALUES(NULL,'$comment')";
// attempt insert query execution
if(mysqli_query($link, $sql)){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
Use below code:-
include ('index.php');
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect("localhost", "x", "", "comment_schema");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(!empty($_POST["comment"])){
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
// Escape user inputs for security
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','$comment')";
$result = mysqli_query($link, $sql);
// attempt insert query execution
if($result){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}else{
die('comment is not set or not containing valid value');
}
Hope it will help you :-)
Some debugging suggestions:
var_dump($_POST); // before mysqli_real_escape_string
var_dump($comment); // after mysqli_real_escape_string
mysqli api may not work well! Fix the query like
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','".$comment."')";
echo $sql; // check your sql syntax
echo mysqli_error($link); // do you have error
Look at your .htaccess file see if you have <Limit POST> tag
Remove this line include ('index.php');. Supposedly, these two files are in one folder. So just run index.php . Tried your code without that line and it worked for me.
Related
I'm trying to insert new record to SQL database using PHP from a HTML form.
I made a form using Post method
<form name="CreatNewMCQ" action="create.php" method="POST">
with a button to submit
<button type="submit" form="CreateNewMCQ">CREATE</button>
what I want to do is when I press the button, it will call create.php which is
<?php
$servername = "localhost";
$user = "admin";
$pass = "admin";
$dbname = "examples";
// Create connection
$conn = new mysqli($servername, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_POST['id'];
$name = $_POST['name'];
$year = $_POST['year'];
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, $name, $year)";
if ($conn->query($sql) === TRUE) {
echo "Tạo mới thành công";
} else {
echo "Lỗi: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
then insert data from form to SQL database (id, name, year from the form).
I got some errors in SQL syntax. What mistake did I make?
Make sure all post values are getting correctly. You should make a condition check before inserting the data, For ex:
$id = isset($_POST['id']) ? $_POST['id'] : '';
$name = isset($_POST['name']) ? $_POST['name'] : '';
$year = isset($_POST['year']) ? $_POST['year'] : '';
if($id && $name && $year){
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, '$name', '$year')";
}else{
return "required fields are missing";
}
NB: Please post your html if possible.
try this:
<?php
/* Attempt MySQL server connection.*/
$servername = "localhost";
$user = "admin";
$pass = "admin";
$dbname = "examples";
$link = mysqli_connect($servername, $user, $pass, $dbname);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$id = $_POST['id'];
$name = $_POST['name'];
$year = $_POST['year'];
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, '$name', '$year')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
HTML Form :
<html>
<form name="test" method="post">
Enter name:<input type="text" name="name"/> <br>
Enter year :<input type="text" name="year"/><br>
<input type="submit" name="save" value="save" />
</form>
</html>
php code :
<?php
$conn=mysql_connect("localhost","root","passward");
$select_db=mysql_select_db("Atul",$conn);
if($conn)
{
echo "connected";
}
else
{
echo "Please try again";
}
if(isset($_POST['save']))
{
$name=$_POST['name'];
$year=$_POST['year'];
$insert_record="insert into test (name,year) values("$name","$year");
$result=mysql_query($insert_record);
if($result)
{
echo "Record inserted successfully";
}
else
{
echo "please try again";
}
}
?>
I have problem with MySQL database, I can't insert the information into the table. My php code seems to work, but when I run it nothing happens.
<?php
$servername = "localhost";
$fname = "fname";
$lname = "lname";
$klas = "klas";
$nomer = "nomer";
$file = "dom";
$dbname = "homeworks";
$conn = new mysqli($servername, $fname, $lname,$klas,$file,$dbname);
$sql = "INSERT INTO student (fname, lname,klas,file)
VALUES ($servername, $fname, $lname,$klas,$file,)";
?>
You have three main problems in your code:
You're still not connected to the database
Only constructing and not executing
Having not matched parameters in the insert values
Solution :
1. Make a connection first
$conn = new mysqli($servername, $username, $password, $dbname);
The Parameter $servername, $username, $password, $dbname is obviously your hostname, Database Username, Password and the Database name
You should not have your table name or column names in the connection parameters
2. Construct the parameters which matches the coloumn name and variables correctly
$sql = "INSERT INTO student (fname, lname,klas,file)
VALUES ($fname, $lname,$klas,$file)";
3. Execute Your Query :
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Note :
Also it's good practice to close your connection once you are done
$conn->close();
So, you should be having something like this
<?php
$servername = "localhost";
$username = "YourDBUsername";
$password = "YourDBPassword";
$fname = "fname";
$lname = "lname";
$klas = "klas";
$nomer = "nomer";
$file = "dom";
$dbname = "homeworks"; //Hope you will have your db name here
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "
INSERT INTO student (fname, lname,klas,file) VALUES
('$fname'
,'$lname'
,'$klas'
,'$file');
";
if ($conn->query($sql) === TRUE) {
echo "New record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Advice :
Always use prepared statements else clean your inputs before you insert.
Your connection should look something like this. link
<?php
//change the data into your connection data
$conn = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
You made your query but didn't execute it.
if (mysqli_query($conn, $sql)) {
echo 'records created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($conn);
}
I have a html form, say example
<form action="form.php" method="post">
First name:<br>
<input type="text" id="fname" name="fname">
<br>
Last name:<br>
<input type="text" id="lname" name="lname">
<br><br>
<input type="submit" value="Submit">
</form>
and form.php
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The form.php is saving that data to database1 .
I want that data to be saved to another database database2 along with database1.
Is it possible ?? If yes then what changes should be made in the code ?
If it is not possible then is it possible to copy data from database1 to database2 automatically? Whenever a new row is added in database1 then it should automatically copied to database2.
I want the same data to be in two different database. How can I achieve any of the above said ??
From php you just have to create new connection to DB.
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
$servernameS = "localhost";
$usernameS = "database2";
$passwordS = "xxxxxxxx";
$dbnameS = "database2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$connS = new mysqli($servernameS, $usernameS, $passwordS, $dbnameS);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($connS->connect_error) {
die("Connection failed: " . $connS->connect_error);
}
//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}
if ($connS->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $connS->error;
}
$conn->close();
$connS->close();
?>
What it sounds like you need is to setup replication.
Here is the official documentation on replication. Here is a simpler step-by-step guide setting it up.
If replication isn't what you wanted, you could accomplish the same thing by connecting to database2 in addition to database1 then running the query once on both.
You can use something like using mysqli::selectDB method:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
/* change db to world db */
$mysqli->select_db("world");
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
$mysqli->close();
?>
Check out the manual.
Similar question as yours at SO.
I'm having problem with updating information in database. The echo pops out as successful but the database row stays blank - why? PHP code:
<?php
if (isset($_POST['gender'])) {
// Sanitize and validate the data passed in
$gender = filter_input(INPUT_POST, 'gender', FILTER_SANITIZE_STRING);
if ($stmt) {
$stmt->bind_param('s', $gender);
$stmt->execute();
$stmt->store_result();
if ($insert_stmt = $mysqli->prepare("INSERT INTO members gender VALUE ?")) {
$insert_stmt->bind_param('s', $gender);
}
}
echo "<div class='notemarg'> Your gender has been submitted</div>";
}
?>
and input form:
<form action="" method="POST">
<input type="radio" name="gender" value="male"> Male <br>
<input type="radio" name="gender" value="female"> Female <br>
<input type="submit" name="gender" value="Set gender" class="button">
</form>
I want to use mysqli->prepare to prevent SQL injection.
I fixed it with alternative way, where there is pre-defined input by button.
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['Female'])) {
$gender = $_POST['Female'];
$sql = "UPDATE members SET gender = '$gender' WHERE username = '".$_SESSION['username']."'";
if ($conn->query($sql) === TRUE) {
echo "<div class='notemarg'> Your gender has been submitted</div>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
And simple form:
<form action="" method="POST">
<input type="submit" name="Female" value="Female" class="button">
</form>
Thanks to all who wanted to help me, especially to anant kumar singh. I could not get that alter idea without his suggestions. Thanks!
UPDATE #1
It just pops out that echo "error"
<?php
if(isset($_POST['Female'])){
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['Female'])) {
$gender = $_POST['Female'];
$stmt = $conn->prepare('UPDATE members
SET gender = ?
WHERE username = ?');
$stmt->bind_param('s', $_POST['Female']);
$stmt->bind_param('s', $_SESSION['username']);
if ($conn->prepare === TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " . $conn->prepare . "<br>" . $conn->error;
}
$conn->close();
}
}
?>
Don't know where is problem...
UPDATE #2
if(isset($_POST['Female'])){
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['Female'])) {
$gender = $_POST['Female'];
$sql = "
UPDATE members
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $_POST['Female']);
$stmt->bind_param('s', $_SESSION['username']);
$stmt->execute();
if ($mysqli->prepare($sql) === TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " . $conn->prepare . "<br>" . $conn->error;
}
$conn->close();
}
}
UPDATE #3
I added also some notes in code so
<?php
// I had here twice the ifisset here and
if(isset($_POST['Female'])){
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//here the second one so I deleted that ifisset here...
$gender = $_POST['Female'];
$sql = "
UPDATE members
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $_POST['Female']);
$stmt->bind_param('s', $_SESSION['username']);
$ok = $stmt->execute();
if ($ok == TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " .$stmt->error; // This is the line that shows the error
}
$conn->close();
}
?>
I'm not sure what is problem... It pops the error on echo "No data supplied for parameters in prepared statement"
Following an answer being posted with a huge security vulnerability, it is worth taking a moment to fix this. There is a way to fix it so you can use your string concatenation approach, but it is generally not as good as parameterisation.
All you need to do is to take your working query, and convert it to a parameterised form. Something like this:
// Expects valid $mysqli object here
$sql = "
UPDATE members
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
// ** As we discovered, the binding needs to happen in one
// ** call, not across several
$stmt->bind_param('ss', $_POST['Female'], $_SESSION['username']);
$stmt->execute();
Looking at your original code, there seems to have been two problems: the statement wasn't prepared at all (and so the program should have exited with a fatal error) and there was a syntax error in the original SQL statement.
In your new code, you're missing the execute() call.
I'm brand new to PHP and just trying to create a very basic registration form but when I click submit it won't create the data in my database.
<form action"signup.php" method="post">
username:<input type="text" name="n"><br />
password:<input type="password" name="p"><br />
id :<input type="text" name="id"><br />
<input type="submit">
</form>
<?php
$conn = mysql_connect("localhost", "root", "");
$db = mysql_select_db("myth", $conn);
?>
<?php
$user = $_POST['n'];
$pass = $_POST['p'];
$id = $_POST['id'];
$sql = "INSERT into phplogin values(" . $id . ",'" . $user . "','" . $pass . "')";
$query = mysql_query();
if(!$query)
echo "failed ".mysql_error();
else
echo "successful";
?>
You're not actually running the query - you need to call mysql_query($sql).
Note that your code is quite vulnerable to things like SQL injection, and mysql_query is a deprecated function in PHP.
First of all, you have not to use mysql_* command as they are deprecated; use mysqli_* or PDO instead.
Second, you have to pass your string at method. In your case: $result = mysql_query($sql);
Remember that $result will return a resource that you have to fetch for obtain your rows
while ($row=mysql_fetch_row($result)) {
// here, you have your rows
}
your script should be like this
<?php
// create connection
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
// check connection
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$user = $_POST['n'];
$pass = $_POST['p'];
$id = $_POST['id'];
$sql = "INSERT into phplogin values('$id','$user','$pass')";
if($mysqli->query($query)) {
printf("New Record has id %d.\n", $mysqli->insert_id);
} else {
printf("Failed ".$mysqli->error);
}
// close connection
mysqli_close($link);
?>
And yes don't use mysql_* as it's deprecated, use mysqli_ or PDO instead.
Try to use mysqli_query as it is better than mysql_query...
<?php
$conn = mysqli_connect("localhost","root","","myth")or die("connection to database problem");
$user = $_POST['n'];
$pass = $_POST['p'];
$id = $_POST['id'];
$sql = "INSERT INTO phplogin VALUES (".$id.",'".$user."','".$pass."')";
$query = mysqli_query($conn, $sql)or die("query error");
if(false===$query)
echo "<br/>".mysqli_error($conn)."<br/><br/><br/>";
else
echo "<br/>done ";
?>
If there is any problem in connection the connection to database problem should occur