hello i am a java developer but new to php here i am trying to insert data in to the database using prepared statements as mentioned in here http://www.php.net/manual/en/pdo.prepared-statements.php but i am getting an error may i know what sort of error is this and any help to resolve this.
Error: Fatal error: Call to undefined method mysqli_stmt::bindParam() in G:****\xampp\htdocs****\registrationControl.php on line 17
<?php
$con = new mysqli("127.0.0.1", "root", "", "ksbka");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['username_first']);
$username_email = mysqli_real_escape_string($con, $_POST['username_email']);
$username_tele = mysqli_real_escape_string($con, $_POST['username_tele']);
echo $firstname."#####".$username_email;
$query="INSERT INTO instructorregistration (Id, Name, email, telephone) VALUES (?, ?, ?, ?)";
$pst = $con->prepare($query);
$pst->bindParam(1, "");
$pst->bindParam(2, $firstname);
$pst->bindParam(3, $username_email);
$pst->bindParam(4, $username_tele);
$pst->execute();
if (!mysqli_query($con,$pst)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
I think if you want to use bindParam() method, the value should be an instance of PDOStatement .
The doc you see as bellow:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$dbh is a PDO instance, I think, NOT mysqli instance. Because there is no mysqli::bindParam().
To solve this problem, you can:
use PDO class instead of Mysqli
create the query as the simplest way:
$query="INSERT INTO instructorregistration (Id, Name, email, telephone) VALUES (NULL, $firstname, $username_email, $username_tele)";
you have to use the mysqli methods, when you use mysqli
$stmt = $con->prepare($query);
$stmt->bind_param(1, "");
...
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
/* explicit close recommended */
$stmt->close();
/* Non-prepared statement */
$res = $mysqli->query("SELECT id FROM test");
var_dump($res->fetch_all());
edit: added some code from the official documentation
Related
I keep getting this error in my php. It worked fine when I hard set the values but doesn't seem to work with variables.
Error: INSERT INTO ContactUS (name, email, subscribed) VALUES (TEST, my#email.com, 1)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Anis, my#email.com, 1)' at line 1
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO ContactUS (name, email, subscribed) VALUES ($name, $email, $subscribed)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Values should be quoted:
$sql = "INSERT INTO ContactUS (name, email, subscribed) VALUES ('$name', '$email', '$subscribed')";
Perhaps it's better to use prepared statements as this is done automatically for you and you won't be vulnerable to SQL injections.
Use quotes around variables, as PHP will replace its value, leaving an invalid query:
$sql = "INSERT INTO ContactUS (name, email, subscribed) VALUES ('$name', '$email', '$subscribed')";
but please use prepared statements, otherwise you'll be victim of SQL injection
does anybody know why i get return value of 0 with this code:
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
$stmt = $mysqli->prepare("INSERT INTO teams (name, token) VALUES (?, ?)");
$stmt->bind_param('ss', $team, $token);
/* execute prepared statement */
$stmt->execute();
if ($stmt->error) {error_log("Error: " . $stmt->error); }
$success = $stmt->affected_rows;
//Get the last insert ID of the insert Team
$lastInsertID = $stmt->insert_id;
//Insert into the Mapping Table
$stmt = $mysqli->prepare("INSERT INTO usersTeamsMap (users_idUser, teams_idTeam) VALUES (?, ?)");
$stmt->bind_param('ii', $userID , $lastInsertID );
/* execute prepared statement */
$stmt->execute();
//Get the last insert ID of the insert Team
$lastInsertID = $stmt->insert_id;
echo "ID: " . $lastInsertID;
The last echo always returns 0. The first " $lastInsertID = $stmt->insert_id;" of the first Insert into query works fine.
Thanks in advance.
EDIT:
Thanks for all answers. Now i know why the service didnt work. My mapping table did not have an AutoIncrement field.
insert_id is an attribute of the mysqli object, not of the statement! It is connection specific.
So it should be $mysqli->insert_id.
I have a prepared mysqli insert statement but when I try to insert data with quotes or double quotes I get this error: Prepare failed: (1064) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Ask me in six months.' We don’t have six months to wait," he said. "I have a p' at line 1
when I use mysqli_real_escape_string around my text that I am trying to insert, it inserts into my database as empty data.
Is there a better way to handle single or double quotes? Or is there something wrong with my code?
$connection = new mysqli("localhost", "username", "password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!($stmt = $connection->prepare("INSERT INTO `in-the-press` (title, `date`, preview, description, image, detailImage, showDetailImage) VALUES ('" . $title . "', '" . $date . "', '" . $preview . "', '" . $description . "','" . $image . "', '" . $detailImage . "', " . $showDetailedImage . ")"))) {
echo "Prepare failed: (" . $connection->errno . ") " . $connection->error;
}else{
$stmt->execute();
echo 'Press has been added <br>';
}
I have tried with mysqli_real_escape_string($title), mysqli_real_escape_string($preview) & mysqli_real_escape_string($description), but like I said it would insert it to the database as empty strings :(
As Micheal said in his comment
Since you're using mysqli with prepare() & execute() you'll be better off harnessing bind_param()
$stmt = $mysqli->prepare("INSERT INTO `in-the-press` (title, `date`, preview, description, image, detailImage, showDetailImage) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('sssssss', $title, $date, $preview, $description, $image, $detailImage, $showDetailedImage);
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
The above is just an example, I don't know what your database schema/structure looks like
Breakdown:
s means string.
d means double.
You can read more on the types (i, s, d, b) in the bind_param link above.
I have the following piece of code to make a input form being written in table named "client" database 'smsmart' which has fields name , address and phone
<?php
define ('DB_USER', 'root');
define ('DB_PASSWORD', '');
define ('DB_HOST', 'localhost');
define ('DB_NAME', 'smsmart');
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("smsmart");
if (!$db_selected) {
die('Can\'t use ' . smsmart . ': ' . mysql_error());
}
$value1 = $_POST['username'];
$value2 = $_POST['address'];
$value3 = $_POST['mobileno'];
$sql = "INSERT INTO client (name,address,phone) VALUES ('$value1', '$value2', '$value3')";
mysql_close();
?>
The fields 'username' 'address' and 'mobileno' from form is not being written into database. What am i doing wrong?
It looks like you're generating the $sql query but not executing it. Given the lack of sanitation on your $_POST inputs, you should probably use a parametric or PDO method to protect yourself against potential SQL attacks.
Here is an example of a parameter-based mySQLi insert.
// connect to the database
$dbConnection = mysqli_connect("localhost", "root", "", "smsmart");
// prepare statement
$stmt = mysqli_prepare($dbConnection, "INSERT INTO client (name,address,phone) VALUES (?,?,?)");
// bind parameters
mysqli_stmt_bind_param($stmt, "sss", $value1, $value2, $value3);
// execute statement
mysqli_stmt_execute($stmt);
// close statement
mysqli_stmt_close($stmt);
// close database connection
mysqli_close($link);
You are saving your query in a variable but that variable isn't doing anything itself
mysql_query($sql);
mysql_query will help you to insert all the data in your Database.
you are missing mysql_query().
$sql = "INSERT INTO client (name,address,phone) VALUES ('$value1', '$value2', '$value3')";
mysql_query($sql);
mysql_close();
$sql = "INSERT INTO client (name,address,phone) VALUES ('$value1', '$value2', '$value3')";
mysql_close();
hence add mysql_query
should be
$sql = "INSERT INTO client (name,address,phone) VALUES ('$value1', '$value2', '$value3')";
mysql_query($sql);
mysql_close();
Everything looks great except one:
Just Use mysql_query() function, Like
$sql = "INSERT INTO client (name,address,phone) VALUES ('$value1', '$value2',
'$value3')";
mysql_query($sql);
mysql_close();
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to prevent SQL injection?
I'm having trouble understanding how to sanitise php against SQL injection and hope someone would be kind enough to explain to me what I need to change here in order to make my code safe?
<?php
$dbConnection = mysqli_connect('****', '****', '****', 'db');
$query = "INSERT INTO `table` (`1`, `2`, `3`) VALUES ('$_POST[1]', '$_POST[2]', '$_POST[3]')";
if (mysqli_query($dbConnection, $query)) {
echo "Successfully inserted " . mysqli_affected_rows($dbConnection) . " row";
} else {
echo "Error occurred: " . mysqli_error($dbConnection);
}
?>
MySQLi supports prepared statements, which is better than manually escaping:
Since you are using procedural MySQLi, here is an example:
/* create a prepared statement */
if ($stmt = mysqli_prepare($dbConnection, "INSERT INTO `table` (`1`, `2`, `3`) VALUES (?, ?, ?)"))
{
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "sss", $_POST[1], $_POST[2], $_POST[3]);
/* execute query */
if(mysqli_stmt_execute($stmt))
{
echo "Successfully inserted " . mysqli_affected_rows($dbConnection) . " row";
}
else
{
echo "Error occurred: " . mysqli_error($dbConnection);
}
/* close statement */
mysqli_stmt_close($stmt);
}
To prevent SQL injections, you could use prepared statements. You'll need some more mysqli_ functions for that:
mysqli_prepare()
mysqli_stmt_bind_param()
mysqli_stmt_execute()
With these you can write something like the following:
$dbConnection = mysqli_connect('****', '****', '****', 'db');
// prepare the query
$query = mysqli_prepare( $dbConnection, "INSERT INTO `table` (`1`, `2`, `3`) VALUES (?, ?, ?)";
// bind parameters; 2nd parameter is for data-types
mysqli_stmt_bind_param( $query, "sss", $_POST[1], $_POST[2], $_POST[3] );
// execute query
if ( mysqli_stmt_execute($query) ) {
echo "Successfully inserted " . mysqli_affected_rows($dbConnection) . " row";
} else {
echo "Error occurred: " . mysqli_error($dbConnection);
}
If you want to keep using the old mysql_* functions look at http://php.net/manual/en/function.mysql-real-escape-string.php
$datapoint1 = mysql_real_escape_string($_POST[1]);
...
$query = "INSERT INTO `table` (`1`, `2`, `3`) VALUES ('$datapoint1', '$datapoint2', '$datapoint3')";
You can use prepared statements or mysqli_real_escape_string