bind_param() Issues - php

I am getting issues with the bind_param function. I will post all the information below.
Error:
Fatal error: Call to a member function bind_param() on a non-object in /home4/lunar/public_html/casino/blogpost.php on line 88
MySQL Error:
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 ':user, :title, :message, :image, :category, NOW())' at line 1
Query:
$user = $_COOKIE['user'];
$title = $_POST['title'];
$message = $_POST['message'];
$image = $_POST['image'];
$category = $_POST['category'];
$stmt = $mysqli->prepare("INSERT INTO `lunar_casino`.`posts` (`id`, `by`, `title`, `message`, `image`, `category`, `date`) VALUES(NULL, :user, :title, :message, :image, :category, NOW())");
echo $mysqli->error;
$stmt->bind_param(":user", $user);
$stmt->bind_param(":title", $title);
$stmt->bind_param(":message", $message);
$stmt->bind_param(":image", $image);
$stmt->bind_param(":category", $category);
$stmt->execute();
if(!$stmt){
echo "<font color='red'><b>There has been an error with our database! Please contact the website administrator!</b></font><br /><br />";
echo $mysqli->error;
} else {
echo "<font color='green'><b>You have successfully added a blog post!</b></font><br /><br />";
}
Any ideas why its like this?

As Rocket Hazmat mentioned you can only use question marks as bind parameter place holder.
You should do something similar:
$stmt = $mysqli->prepare("INSERT INTO `lunar_casino`.`posts` (`id`, `by`, `title`, `message`, `image`, `category`, `date`) VALUES(NULL, ?, ?, ?, ?, ?, NOW())");
$stmt->bind_param("sssss", $user, $title, $message, $image, $category);
More details: http://www.php.net/manual/en/mysqli-stmt.bind-param.php

$stmt->bind_param("sssss", $user, $title, $message, $image, $category);
on the first argument the s = string and i = integer. You need to specify which type of value you want to add to the database. If you want to add 5 values that are strings to the database then write 'sssss' if you want to insert 5 integers then write 'iiiii' if you have some integers values and some string values then you can adjust accordingly.
//so if your values are all strings then this would be correct :
$stmt->bind_param("sssss", $user, $title, $message, $image, $category);
//so if your values are all integers then this would be correct :
$stmt->bind_param("iiiii", $user, $title, $message, $image, $category);
//if the first 2 are integers and the other 3 strings then this would be correct :
$stmt->bind_param("iisss", $user, $title, $message, $image, $category);
and so on.

Related

Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number

I am receiving this error and am unable to figure out why.
Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in C:\xampp\htdocs\insert.php on line 32
$SELECT = "SELECT id FROM heroes WHERE name = ? LIMIT 1";
$INSERT = "INSERT INTO heroes (id, name, title, bp, ticket, diamond) VALUES ('NULL', '$name', '$title', '$bp', '$ticket', '$diamond')";
//Prepare statement
$stmt = $connection->prepare($SELECT);
$stmt->bind_param("s", $name);
$stmt->execute();
$stmt->bind_result($name);
$stmt->store_result();
$rnum = $stmt->num_rows;
if ($rnum==0){
$stmt->close();
$stmt = $connection->prepare($INSERT);
$stmt->bind_param("sssss", $name, $title, $bp, $ticket, $diamond);
$stmt->execute();
echo "New hero inserted successfully, sir!";
} else {
echo "There is already a hero with this name, sir!";
}
$stmt->close();
$connection->close();
You don't actually have any params to bind in your insert:
$INSERT = "INSERT INTO heroes (id, name, title, bp, ticket, diamond) VALUES ('NULL', '$name', '$title', '$bp', '$ticket', '$diamond')";
Do this:
$INSERT = "INSERT INTO heroes (name, title, bp, ticket, diamond) VALUES (?, ?, ?, ?, ?)";
Then the values you bind replace the question marks.
Also note there is a very significant difference between NULL and 'NULL' -- the latter is a string. If you have an auto-incrementing ID field, just leave it out of the insert and the database will fill it in for you.

Mysqli bind parameters not working

I'm trying to use prepared statements to enter data in a database. The unprepared statement works but this prepared statement does not. I can't find out why.
Prepared version:
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
$stmt->execute();
Unprepared version:
$sql = "INSERT INTO videos (file_name, upload_by, date, path) VALUES ('$newstring', '$id', '
$date', 'Nominator/$location$newstring')";
mysqli_query($mysqli, $sql);
Replace $stmt-execute(); with $stmt->execute();
Also, don't use date and path in query. Rename them with some other name like date1 and path1.
Update your Query like below that will surely work (Tested Offline):
<?php
$mysqli = new mysqli('localhost', 'root', '', 'test2');
if ($mysqli->errno) {
printf("Connect failed: %s\n", $mysqli->error);
exit();
}
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date1, path1) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $file_name, $upload_by, $date1, $path1);
$date1 = date("Y-m-d");
$file_name = "test.jpg";
$upload_by = "amit";
$path1 = "test";
if ($result = $stmt->execute()){
echo "success";
$stmt->free_result();
} else {
echo "error";
}
$stmt->close();
?>
You are binding your parameter twice, if you are using only ?, don't bind parameter again just execute directly.
//Prepare your query first
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
//Just pass your argument and execute directly without binding the parameter (The parameter is binded already)
$stmt->execute('ssss', $newstring, $id, $date->format('Y-m-d'), $location);

sql error when submitting with php

My php files that submits an entry to a database table isn't working and I can't figure out why. It takes in an Ajax submit and I know that the problem isn't with the data, or the Ajax request as it processes as a success. The only issue is that no data is ever submitted to my database. I had this working before I changed to code to concatenate the address string where it was one variable before. Any advice would be great!
Here is the php files
UPDATE:::THIS IS THE UPDATED PHP FILE
<?php
require("dbinfo.php");
// Create connection
$conn = new mysqli('localhost', $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = $_POST['user_name'];
$street = $_POST['user_street'];
$city = $_POST['user_city'];
$state = $_POST['user_state'];
$country = $_POST['user_country'];
$zip = $_POST['user_zip'];
$address = $street.', '.$city.', '.$state.', '.$country.', '.$zip;
$shortAdd = $city.', '.$state.', '.$country;
$type = $_POST['user_color'];
$desc = $_POST['user_message'];
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$address."&sensor=true";
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;
if ($status=="OK") {
$lat = $xml->result->geometry->location->lat;
$lon = $xml->result->geometry->location->lng;
}
$sql = "INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`, `desc`)
VALUES (?, ?, ?, ?, ?, ?);";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssssss', $name, $shortAdd, $lat, $lon, $type, $desc);
$stmt->execute();
$conn->close();
?>
While docliving's answer is correct, please take the extra step and use prepared statements. Your code is vulnerable to SQL injection attacks without it. It just takes a very minor change to convert it to use prepared statements. Here is how to do it with mysqli:
$sql = "INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`, `desc`)
VALUES (?, ?, ?, ?, ?, ?);";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssssss', $name, $shortAdd, $lat, $lon, $type, $desc);
$stmt->execute();
When #MySelfBoy wrote:
After the assignment, you have to execute SQL statements
He means that you have to execute your query
$sql = "INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`, `desc`)
VALUES ('$name', '$shortAdd', '$lat', '$lon', '$type', '$desc');";
with the following instruction:
$conn->query($sql);
NOTE: I Still canĀ“t make comments, so I'm posting it here.

SQL syntax error when value is entered for parameter

I have this line of code to enter data into a database using binding:
$mysql = "INSERT INTO Orders (`Name`, `Recipient`, `Destination`, `Room`, `Message`, `Anonymous`, `OffCampus`, `OffCampusAddress`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($con,$mysql);
Oddly enough, this error only occurs when a value for the column Recipient is entered in the html form. When nothing is entered in the field it works. The error is:
mysqli error: 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 '0' at line 1
Could anyone tell me why entering a value for the parameter would cause a MySQL syntax error? Thanks in advance, and sorry if it's obvious, I'm new to web development.
Here is my binding:
mysqli_stmt_bind_param($stmt, 'ssssssss', $name, $recipient, $destination, $room, $message, $anonymous, $offcampus, $offcampusaddress);
I think you should do like this as in my below code.
$mysqli = new mysqli('localhost', 'root', '', 'DBNAME');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO Orders (`Name`, `Recipient`, `Destination`, `Room`, `Message`, `Anonymous`, `OffCampus`, `OffCampusAddress`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssdssss", $Name, $Recipient, $Destination, $Room, $Message, $Anonymous, $OffCampus, $OffCampusAddress);
$Name= 'DEU';
$Recipient= 'Bavarian';
$Destination= "XYZ";
$Room= 15;
$Message= 'May I help you';
$Anonymous= 'i do not know';
$OffCampus= "YY";
$OffCampusAddress= "Known Street";
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
In bind parameters (sssdssss) means the the type of parameter as you given as input. s for string value, and d for decimal value.
I keep sssdssss because, d is decimal i.e. no: of rooms and this type comes first, if in your db, you keep it varchar so you may convert d to s.
you have write wrong syntax in you question i.e.
mysqli_stmt_bind_param($stmt, 'ssssssss', $name, $recipient, $destination, $room, $message, $anonymous, $offcampus, $offcampusaddress);
Hope it will help you.
Thanks

sqlite php getting unrecognized token: ":" error while inserting and parameterized query

I am working with sqlite for the first time.
Preparing a query string like
$articleInsertQuery = "INSERT INTO Articles VALUES (?, ?, ?, ?, ?)", ($i, $title, $content, $date, 93,);
It returns "Parse error". I also tried without passing parametrized query like
$articleInsertQuery = "INSERT INTO Articles VALUES ($i, $title, $content, $date, 93)";
ANd getting "Unable to prepare statement: 1, unrecognized token: ":" "
Any idea where I am doing wrong?
#arnoldIf you are using PDO for that.
The way to prepare and execute your query would be as follows.
$dbObject = new PDO('sqlite:sqlitedb');// NEW LINE
$articleInsertQuery = "INSERT INTO Articles VALUES (?, ?, ?, ?, ?)";
$query = $dbObject->prepare($articleInsertQuery);
$query->execute(array($i, $title, $content, $date, 93));
EDIT:
See sqlite3 prepare.
$articleInsertQuery = "INSERT INTO Articles VALUES (:i, :title, :content, :date, :int)";
$query = $dbObject->prepare($articleInsertQuery);
$query->bindValue(':i', $i, SQLITE3_INTEGER);
$query->bindValue(':title', $title, SQLITE3_TEXT);
$query->bindValue(':content', $content, SQLITE3_TEXT);
$query->bindValue(':date', $date, SQLITE3_TEXT);
$query->bindValue(':int', 93, SQLITE3_INTEGER);
$result = $query->execute();
Hope this helps.

Categories