Store the data in mysql - php

i want to store a data to the mysql database but if i press the submit button it display the php page.
form:
<div id="test">
<form action="demo.php" method="post">
please enter the number(1 to 100) : <input type="text" name="value">
<input type="submit">
</form>
</div>
demo.php
<?php
$value=$_POST['value'];
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "clock";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO input VALUES (".$_POST['value'].")";
if ($conn->query($input) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Replace $input with $sql in the if statement:
From
if ($conn->query($input) == TRUE) {
To
if ($conn->query($sql) == TRUE) {
Note: Since you are storing $_POST['value'] in $value, you don't need to use $_POST['value'] in the query, instead make use of $value.

There is one correction:
Change
if ($conn->query($input) == TRUE) {
To:
if ($conn->query($sql) == TRUE) {
Along with that, following are suggestions:
$sql = "INSERT INTO input VALUES (".$_POST['value'].")";
This query is OK, is value of $_POST['value'] is integer, but, for strings, it will create SQL Syntax Error.
Please correct this to:
$sql = "INSERT INTO input VALUES ('".$_POST['value']."')";
Observe, enclosed semi colon.
2) You are inserting only one field value and not specifying fields. This means you table has only field. Normally we do not have tables with only one field.
Please specify field names:
$sql = "INSERT INTO input (field_one) VALUES (".$_POST['value'].")";

Get values like this
$value=$_REQUEST['value'];
change the query to
$sql = "INSERT INTO input VALUES ('$value')";

1st : Add name attribute to submit button name="submit"
<input name="submit" type="submit">
2nd : use isset like this if(isset($_POST['submit'])){ //rest of code here }
3rd : Try to use prepared statement or pdo to avoid sql injection
demo.php
<?php
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "clock";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$stmt = $conn->prepare("INSERT INTO input(value) VALUES (?)");
$stmt->bind_param('s',$_POST['value']);
//The argument may be one of four types:
//i - integer
//d - double
//s - string
//b - BLOB
//change it by respectively
if ($stmt->execute() == TRUE && $stmt->affected_rows>0) {
echo "New record created successfully";
} else {
echo "Error: <br>" . $conn->error;
}
}
$conn->close();
?>

Related

Insert Data to MySQL db from HTML form using PHP

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";
}
}
?>

Php to MySQL database

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);
}

Entering data into mysql database using php

Customer will complete a form and enter a pathway where they will want the CSV to be exported to. The pathway is entered using the top section of the php (below):
<form action="register.php" method="post">
Enter file pathway where CSV will be saved: <input type="text" name="username" required="required"/> <br/>
<input type="submit" value="Enter"/>
</form>
</body>
I want to create a variable called pathway. At the moment I can get text entered into the correct row in the mysql database (I can get John printed in the database), but not the correct text that was entered into the form (i.e. $pathway).
I want to create a variable because after saving the pathway in the database i also want to use it in an export.php.
I am assuming i also need something like this:
if($_SERVER["REQUEST_METHOD"] == "POST"){
$pathway = mysql_real_escape_string($_POST['pathway']);
// but i can't seem to piece it altogether.
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "first_db";
$table_users = $row['pathway'];
$pathway = "pathway";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (pathway)
VALUES ('John')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
This shoud work, if not then check your usename and password...
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "first_db";
$pathway = $_POST['username']; username - is the name of your input.
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (pathway)
VALUES ('$pathway')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
your DB username is Null
Change $username = ""; to $username = "root";
Your input field name is username
change it to pathway for $_POST['pathway'] to work
<form action="register.php" method="post">
Enter file pathway where CSV will be saved:
<input type="text" name="pathway" required="required"/> <br/>
<input type="submit" value="Enter"/>
</form>
First of all, you've got 'username' as the name of the field using for type a pathway, so rename it to 'pathway'.
I don't know if I understand you, but do you just want to read posted content?
Try something like:
$pathway = $_POST['pathway']
I strongly recommend to use object-oriented style with
$conn = new mysqli...
and then
mysqli->prepare(), mysqli->bind_param(), mysqli->execute()
With this you won't have to deal with mysqli_real_escape_string etc.

PHP SQL : How to save data to multiple database from one html form OR how to copy data from one database to another database automatically

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.

Inputted values not saved while inserting data from html form into sql database (html,php,sql)

The problem: insert.php connects fine, but only inserts empty values ('') when I hit 'save' on the html form. The text I type, which I'm trying to insert, isn't saved. Somewhere a connection isn't being made and that data is lost but I can't figure out exactly where. Any help?
HTML insert form (collecting data for 2 parameters, 'user' and 'thread')
<form action="insert.php" method="post">
user: <input type="text" name="user"><br>
thread: <input type="text" name="thread"><br>
<input type="submit" value="Save">
</form>
PHP code to connect to SQL, insert inputted values
<?php
$user = $_POST['user'];
$thread = $_POST['thread'];
$servername = "##.##.###";
$username = "harwoodjp";
$password = "~";
$dbname = "332";
//create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("SQL (&#9746)<br/> " . $conn->connect_error);
}
echo "SQL (&#9745) <br/>";
$sql = mysql_connect($servername,$username,$password);
mysql_connect($servername,$username,$password);
mysql_select_db("332project");
//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);
echo "<script>window.location='select.php'</script>"; //select.php displays the full table
//close MySQL
mysql_close($sql);
?>
try this
<?php
$user = $_POST['user'];
$thread = $_POST['thread'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
//create connection
$conn = mysql($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("SQL (&#9746)<br/> " . $conn->connect_error);
}
echo "SQL (&#9745) <br/>";
$sql = mysql_connect($servername,$username,$password);
mysql_select_db("db");
//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);
echo "<script>window.location='select.php'</script>"; //select.php displays the full table
//close MySQL
mysql_close($sql);
?>
It might be because the default form posting method is GET.
Either change your $_POST to $_GET or add method="POST" to your form tag.

Categories