Reputation:
I am using ampps server for my database. Using php I have written script to connect with server database. Now I want to insert data in the database table.
I tried writing the script and new row is getting inserted with null values.
I tried multiple insert queries but did not succeed.
<?php
require("testDB.php");
class insertUserHelper
{
private $name;
private $email;
private $status;
function insertUserHelper($name,$email,$status)
{
$this -> name = $name;
$this -> email = $email;
$this -> status = $status;
}
function insert()
{
$con = testDatabase::getDB();
echo $name;
echo $email;
echo $status;
$sql = "INSERT INTO user ". "(name,email,status) ".
"VALUES ". "('$name','$email','$status')";
if (mysqli_query($con, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
}
?>
Can anyone help please,very new to php. Thank you..
Upvotes: 1
Views: 105
Reputation: 10548
$this->name
, $this->email
, $this->status
instead of $name
, $email
, $status
.UPDATED CODE
function insert()
{
$con = testDatabase::getDB();
$stmt = mysqli_prepare($con, "INSERT INTO user (name,email,status) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $this->name, $this->email, $this->status);
if (mysqli_stmt_execute($stmt)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
For More Info, Click mysqli_stmt::bind_param
EXPLANATION
$stmt->bind_param("sss", $firstname, $lastname, $email);
The sss
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:
We must have one of these for each parameter. By telling mysql what type of data to expect, we minimize the risk of SQL injections.
For more info, click Prepared Statements
Upvotes: 0
Reputation: 437
please replace
$sql = "INSERT INTO user ". "(name,email,status) ".
"VALUES ". "('$name','$email','$status')";
with
$sql = "INSERT INTO user ". "(name,email,status) ".
"VALUES ". "('$this->name','$this->email','$this->status')";
Upvotes: 0
Reputation: 134
try this
$sql = "INSERT INTO user (name,email,status) VALUES ('$name','$email','$status')";
Upvotes: 1
Reputation: 2092
You are creating local variables $name, $email and $status
in your insert() function, try using $this->name, $this->email and $this->status
instead. And use a prepared statement with bind variables instead of building a vulnerable query like that.
Upvotes: 1