Inserting Data Using MySQLi

insert record using mysqli with one page

Working Code just copy and paste it

<html>
<head></head>
<body>
<form method = "post" action = "<?php echo $_SERVER['PHP_SELF']; ?>">
Message: <input type = "text" name = "message">
</br></br>
<input type = "submit" name = "submit">
</form>

<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['message'])) {
$conn = mysqli_connect("localhost", "root", "", "dbase");
$message = $_POST['message'];

$sql = "INSERT INTO tblmessage (message_id, message) VALUES (NULL, '" . $message . "')";
$insert = mysqli_query($conn, $sql);
mysqli_close($conn);
if ($insert) {
echo "Message successfully added!";
} else {
echo "Error" . mysqli_error($conn);
}
}
}
?>
</body>
</html>

Inserting data to table (mysqli insert)

Warning: Never ever refer to w3schools for learning purposes. They have so many mistakes in their tutorials.

According to the mysqli_query documentation, the first parameter must be a connection string:

$link = mysqli_connect("localhost","root","","web_table");

mysqli_query($link,"INSERT INTO web_formitem (`ID`, `formID`, `caption`, `key`, `sortorder`, `type`, `enabled`, `mandatory`, `data`)
VALUES (105, 7, 'Tip izdelka (6)', 'producttype_6', 42, 5, 1, 0, 0)");

Note: Add backticks ` for column names in your insert query as some of your column names are reserved words.

php mysqli insert data into two tables

I can't really see what's exactly wrong with your code, it might happen that some of the columns on the parta table are not supposed to be null. With the code you provided, it's hard to tell, as there's no error handling at all. You might want to use transactions, then use proper error handling and also use prepared statements.

Try with this code that I have prepared for you.

<?php
$con = new mysqli("..."); // you should know this part already

$success = false;
try {

$con->autocommit(FALSE);

$con->begin_transaction();

if ($sql = $con->prepare("INSERT INTO socio (name, age, dob, gender, year, stgroup, stadd) VALUES (?,?,?,?,?,?,?)")) {
$sql->bind_param('sissss', $stnam, $stage, $stdob, $stgen, $styer, $stGr, $stadd);
if (!$sql->execute()) {
throw new Exception($sql->error);
}

if ($sql_two = $con->prepare("INSERT INTO parta (name, stgroup, year) VALUES (?,?,?)")) {
$sql_two->bind_param('sss', $stnam, $stGr, $styer);
if (!$sql_two->execute()) {
throw new Exception($sql_two->error);
}
}
}

if ($con->commit()) {
$success = true;
} else {
throw new Exception('Transaction commit failed...');
}
}catch (Exception $ex) {
try {
// something went wrong,rollback and display message
$con->rollback();
echo $ex->getMessage();
}
catch (Exception $e) {
echo $e->getMessage();
}
}
$con->autocommit(TRUE);

if ($success) {
echo "data successfully inserted";
}
?>

PHP: Inserting Values from the Form into MySQL

The following code just declares a string variable that contains a MySQL query:

$sql = "INSERT INTO users (username, password, email)
VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

It does not execute the query. In order to do that you need to use some functions but let me explain something else first.

NEVER TRUST USER INPUT: You should never append user input (such as form input from $_GET or $_POST) directly to your query. Someone can carefully manipulate the input in such a way so that it can cause great damage to your database. That's called SQL Injection. You can read more about it here

To protect your script from such an attack you must use Prepared Statements. More on prepared statements here

Include prepared statements to your code like this:

$sql = "INSERT INTO users (username, password, email)
VALUES (?,?,?)";

Notice how the ? are used as placeholders for the values. Next you should prepare the statement using mysqli_prepare:

$stmt = $mysqli->prepare($sql);

Then start binding the input variables to the prepared statement:

$stmt->bind_param("sss", $_POST['username'], $_POST['email'], $_POST['password']);

And finally execute the prepared statements. (This is where the actual insertion takes place)

$stmt->execute();

NOTE Although not part of the question, I strongly advice you to never store passwords in clear text. Instead you should use password_hash to store a hash of the password

MySQLi insert query not reading values from form, inserting blank data

<?php
require "connection.php";
require "search.php";
// You can remove the need to escape your strings by using prepared statements.

The check with REG is unnecessary. Best to remove it.

if(isset($_POST['Register'])){

$stmt = $conn->prepare("SELECT null FROM users WHERE username = ? ");
$stmt->bind_param("s", $_POST['username']);
$stmt->execute();
if($stmt->fetch()){
$error = "Username exists.";
}
else{
$error = "";
}
$stmt->close();

if($error == ""){
$param = "Active";
$stmt = $conn->prepare("INSERT INTO users(username, password, email, acc_active) VALUES(?,?,?,?)");
$stmt->bind_param("ssss", $_POST['username'], $_POST['password'], $_POST['email'], $param);
$stmt->execute();
$stmt->close();
}
else
{
echo $error;
}

}

Assuming your form is on the same page, you can simply remove the action you add previous. Else you can keep it, but remove the REG.

 <form method="post" action="" style="text-align: center">
<input type="text" placeholder="Username..." name="username" >
<input type="text" placeholder="Email..." name="email" />
<input type="password" placeholder="Password..." name="password">
<input type="password" placeholder="Confirm Password..." name="password-confirm">

<a href="/rail/login">Return / Cancel</a>
<input type="submit" name="Register" value="Register">
</form>


Related Topics



Leave a reply



Submit