I am using ajax and I can't tell what the error is, but I am certain that the data has been inserted in my database. Here is what I tried:
if(isset($_POST['user_id']) && isset($_POST['content']) && isset($_POST['date']) && isset($_POST['category_id'])){
$content = $_POST['content'];
$date = $_POST['date'];
$user_id = $_POST['user_id'];
$category_id = $_POST['category_id'];
$stmt = $db->prepare("INSERT INTO post_items(`post_id`,`content`,`date`,`user_id`,`category_id`)
VALUES (?,?,?,?)");
$stmt = bind_param('ssii',$content,$date,$user_id,$category_id);
if($stmt->execute()) {
echo mysqli_insert_id($db);
}else{
echo "Something is wrong. Insert failed..";
}
}
My old working version (with the lack of security) is shown below:
if(isset($_POST['user_id']) && isset($_POST['content']) && isset($_POST['date']) && isset($_POST['category_id'])){
$content = $_POST['content'];
$date = $_POST['date'];
$user_id = $_POST['user_id'];
$category_id = $_POST['category_id'];
/* $result = $db->query("INSERT INTO post_items(`content`,`date`,`user_id`,`category_id`)
VALUES (".$content."', '".$date."', '".$user_id."', '".$category_id."')");*/
$stmt = $db->prepare("INSERT INTO post_items(`post_id`,`content`,`date`,`user_id`,`category_id`)
VALUES (?,?,?,?)");
$stmt = bind_param('ssii',$content,$date,$user_id,$category_id);
if($stmt->execute()) {
echo mysqli_insert_id($db);
}else{
echo "Something is wrong. Insert failed..";
}
}
I am not sure what I did wrong here as it is the first time that I have worked with this material.
First of all, you don't bind the same number of parameters as value you assign...
Also, The way you are using bind_param is wrong. It should be
if(isset($_POST['user_id']) && isset($_POST['content']) && isset($_POST['date']) && isset($_POST['category_id'])){
$content = $_POST['content'];
$date = $_POST['date'];
$user_id = $_POST['user_id'];
$category_id = $_POST['category_id'];
$stmt = $db->prepare("INSERT INTO post_items(`content`,`date`,`user_id`,`category_id`)
VALUES (?,?,?,?)");
$stmt->bindParam(1, $content);
...
$stmt->bindParam(4, $category_id);
if($stmt->execute()) {
echo mysqli_insert_id($db);
}else{
echo "Something is wrong. Insert failed..";
}
}
or you could also do the following :
if(isset($_POST['user_id']) && isset($_POST['content']) && isset($_POST['date']) && isset($_POST['category_id'])){
$content = $_POST['content'];
$date = $_POST['date'];
$user_id = $_POST['user_id'];
$category_id = $_POST['category_id'];
$stmt = $db->prepare("INSERT INTO post_items(`content`,`date`,`user_id`,`category_id`)
VALUES (?,?,?,?)");
if($stmt->execute(array($content,$date,$user_id,$category_id))) {
echo mysqli_insert_id($db);
}else{
echo "Something is wrong. Insert failed..";
}
}
also just to let you know, pdo has a method to fetch the last id, so instead of
mysqli_insert_id
you could use
$stmt->lastInsertId()
if(isset($_POST['user_id']) && isset($_POST['content']) && isset($_POST['date']) && isset($_POST['category_id'])){
$content = $_POST['content'];
$date = $_POST['date'];
$user_id = $_POST['user_id'];
$category_id = $_POST['category_id'];
$stmt = $db->prepare("INSERT INTO post_items(`content`,`date`,`user_id`,`category_id`)
VALUES (?,?,?,?)");
$stmt->bindParam(1, $content);
...
$stmt->bindParam(4, $category_id);
if($stmt->execute()) {
echo $stmt->lastInsertId();
}else{
echo "Something is wrong. Insert failed..";
}
}
Related
Im trying to add data to diferent tables in MySQL, but at the moment of run my code, it shows me a error is it "Fatal error: Uncaught Error: Call to a member function query()", is the firs time that y use the query function so I don't know whats going wrong.
<?php
session_start();
$_SESSION['ID_user'];
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = '$id' LIMIT 1");
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "UPDATE user SET Name_user='$name', password='$password' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->bindParam(':name', $_POST['name'], FILTER_SANITIZE_SPECIAL_CHARS);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $result['name'];
$lastid = $conn->query("SELECT last_insert_id()")->fetch();
$insert = "INSERT INTO rel_company_user (ID_user) VALUES ('$id')";
$in = $conn->prepare($insert);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES ('$company')";
$in = $conn->prepare($insert);
$in->execute();
$update = "UPDATE rel_company_user SET ID_company='$lastid' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>
You should use parameters in all your queries. And you can't use bindParam() if you didn't put a placeholder in the query.
FILTER_SANITIZE_SPECIAL_CHARS is not a valid argument to bindParam(). The third argument is an optional data type.
You never set $thelast anywhere, that should be $conn.
If $id is already assigned, you can't use LAST_INSERT_ID() to get ID_user. Just insert that value into the user table.
You don't need to perform a query to get the last insert ID. Just use LAST_INSERT_ID() in the VALUES list of the next INSERT query.
You can't fetch the results of an UPDATE query.
You can't get the last insert ID if you haven't done an insert. The UPDATE user query should be INSERT INTO user.
In several places you assigned the SQL to $insert, but then did $conn->prepare($update).
<?php
session_start();
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = :id LIMIT 1");
$resultset->bindParam(':id', $id);
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "INSERT INTO user (ID_user, Name_user, password) VALUES (:id, :name, :password)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->bindParam(':name', $name);
$up->bindParam(':password', $password);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $name;
$insert = "INSERT INTO rel_company_user (ID_user) VALUES (:id)";
$in = $conn->prepare($insert);
$in->bindParam(':id', $id);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES (:company)";
$in = $conn->prepare($insert);
$in->bindParam(':company', $company);
$in->execute();
$update = "INSERT INTO rel_company_user (ID_company, ID_user) VALUES (LAST_INSERT_ID(), :id)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>
The code I have below is suppose to insert some information into a mysql database. For some reason every time I test it I get the error statement that it was not able to execute. Everything looks like it should work to me. Is there something I am missing here?
<?php
include("phpconnect.php");
$name = $_GET["name"];
$date = $_GET["date"];
echo $name;
echo $date;
$sql = "INSERT INTO main (name, visits, visitDate, lastVisit)
VALUES ('$name', '1', '$date', '$date')";
if (mysqli_query($conn, $sql))
{
echo "Records added successfully.";
}
else
{
echo "ERROR: Could not execute $sql. "
.mysqli_error($conn);
}
mysqli_close($conn);
?>
Maybe, you should build your SQL statement slightly different. You can always throw an error message, better for the overview -
$sql = "INSERT INTO main (name, visits, visitDate, lastVisit)
VALUES (?, 1, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
$stmt->bind_param('sss', $name, $date, $date);
if (!$stmt->execute()) {
return false;
// or print error message
} else {
return true;
} else {
return false;
}
Or check this out - MySQL INSERT INTO with PHP $variable !
First Check your datbase connection
Second check your form method GET or POST then apply
Check your table column name
include("phpconnect.php");
if(isset($_POST['submit'])){
$name = $_POST["name"];
$date = $_POST["date"];
$sql = "INSERT INTO main (name, visits, visitDate, lastVisit) VALUES ('$name', '1', '$date', '$date')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
Try something like this. This function accurately inserts into my database and also scrapes for SQL injection.
function addRestaurant() {
if(isset($_POST['submit'])) {
global $connection;
$name = $_POST['name'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$googlemapslink = $_POST['googlemapslink'];
$restauranttype = $_POST['restauranttype'];
$website = $_POST['website'];
$logo = $_POST['logo'];
$sitelink = $_POST['sitelink'];
if ($googlemapslink == "") {
$googlemapslink = "https://youtu.be/dQw4w9WgXcQ";
}
if ($website == "") {
$website = "https://youtu.be/dQw4w9WgXcQ";
}
if ($logo == "") {
$logo = "https://youtu.be/dQw4w9WgXcQ";
}
$name = mysqli_real_escape_string($connection, $name);
$address = mysqli_real_escape_string($connection, $address);
$city = mysqli_real_escape_string($connection, $city);
$state = mysqli_real_escape_string($connection, $state);
$zipcode = mysqli_real_escape_string($connection, $zipcode);
$googlemapslink = mysqli_real_escape_string($connection, $googlemapslink);
$restauranttype = mysqli_real_escape_string($connection, $restauranttype);
$website = mysqli_real_escape_string($connection, $website);
$logo = mysqli_real_escape_string($connection, $logo);
$sitelink = mysqli_real_escape_string($connection, $sitelink);
$query = "INSERT INTO `restaurants` (Name, Address, City, State, ZipCode, GoogleMapsLink, Website, RestaurantType, RestaurantLogo, SiteLink) ";
$query .= "VALUES (";
$query .= "'$name', ";
$query .= "'$address', ";
$query .= "'$city', ";
$query .= "'$state', ";
$query .= "'$zipcode', ";
$query .= "'$googlemapslink', ";
$query .= "'$website', ";
$query .= "'$restauranttype', ";
$query .= "'$logo', ";
$query .= "'$sitelink'); ";
$filesite = "restaurants/" . $sitelink;
$file = "restaurants/menu.php";
$contents = file_get_contents($file);
file_put_contents($filesite, $contents);
$result = mysqli_query($connection, $query);
if(!$result) {
die("Query failed." . mysqli_error($connection));
} else {
echo "Record updated!";
}
}
}
I had created a database which named student with ID, name, mat_number, specialty, age, and gender, in a PHP application.
I do not want the name or mat_number be taken in more than once.
I have done the connection to my database in a different page and called it in the add student page.
This following codes is for a faculty database collection
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender))
{
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}
else{
echo "Error: Complete all records";
}
}
?>
I want to get an error message demanding for a change if the 2 fields already exist in the database.
first name to check in database if already exist the record.
if no record run sql insert command.
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
$sql = "SELECT * FROM `student` WHERE name = "'.$name.'" and UB_number = '".$matNo."'";
$conn->query($sql);
$cnt = $conn->rowCount();
if($cnt == 0){
$sql = "INSERT INTO `student`
(`name`, `UB_number`, `age`,`sex`, `specialty`)
VALUES
('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}else{
echo "Error: Complete all records";
}
}
If you would like to insert a new record to DB only if one doesn't exist which has the same name or mat_number then you first need to execute SELECT statement to see if it exists.
Using MySQLi:
<?php
include 'mysqli.php';
$conn = $mysqli;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->bind_param('ss', $name, $matNo);
$stmt->execute();
$stmt->bind_result($exists);
$stmt->fetch();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)');
$stmt->bind_param('sssss', $name, $matNo, $age, $gender, $specialty);
$stmt->execute();
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
Using PDO:
<?php
include 'lib.php';
$conn = $pdo;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->execute([$name, $matNo]);
$exists = $stmt->fetchColumn();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)')
->execute([$name, $matNo, $age, $gender, $specialty]);
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
hope this may be helpfull to you. In here I asume that you are not using any framework. But if you use a framework there are plenty of easy methods to do this.In here I have checked only name field. You should update code as you wants. Also it it better if you could validate your inputs before check. Like trim(). Thanks
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
//after user click the submit button
$sql_Select_Stundets = "SELECT * FROM student WHERE name = '$name' ";
// query the sql with db connection
$result_sql_Select_Stundets = mysqli_query($conn,$sql_Select_Stundets);
//Now check the row count to verify the output if there is any match
$rowcount=mysqli_num_rows($result);
//Now write insert inside if condition
if( $rowcount >0 ) {
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender)) {
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
bheader("Location: index.php");
}else{
echo "Error: Complete all records";
}
}else{
echo "<script>
alert('sorry this name is already available');
</script>";
}
}
?>
When I login it's suppose to insert, but instead does nothing.. On my register php it inserts data to accounts, but when i insert data into online it won't work..
PS- I'm new to PDO so I don't know what i'm doing wrong
<?php
session_start();
if(isset($_SESSION['users']) != ""){
echo '<script type="text/javascript">','index();','</script>';
}
include('../php/dbConnect.php');
$username = $_POST['username'];
$password = $_POST['password'];
$query = 'SELECT * FROM `accounts` WHERE username = ?';
$queryprepare = $conn->prepare($query);
$queryprepare->bindParam(1, $username, PDO::PARAM_STR);
$queryprepare->execute();
$row = $queryprepare->fetch();
if($row['password'] == md5($password))
{
$_SESSION['online'] = true;
$_SESSION['users'] = $username;
$_SESSION['userid'] = $row['id'];
$_SESSION['name'] = $row['name'];
$_SESSION['age'] = $row['age'];
$_SESSION['image'] = $row['image'];
$check_row = 'SELECT * FROM `online` WHERE username = ?';
$check_row_fetch = $conn->prepare($check_row);
$check_row_fetch->bindParam(1, $username, PDO::PARAM_STR);
$check_row_fetch->execute();
$number_of_rows = $check_row_fetch->rowCount();
if($number_of_rows != 0) {
echo '<script type="text/javascript">','redirect();','</script>';
}
else{
$online_insert = 'INSERT INTO online (username, name, age, image) VALUES (?, ?, ?, ?)';
$online_insert_fetch = $conn->prepare($online_insert);
$online_insert_fetch->bindParam(1, $SESSION['users'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(2, $SESSION['name'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(3, $SESSION['age'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(4, $SESSION['image'], PDO::PARAM_STR);
$online_insert_fetch->execute();
echo '<script type="text/javascript">','redirect();','</script>';
}
}
else{
echo("Wrong Credentials");
}
?>
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I am a coding beginner and can't solve this error.I tried to create a login/register script but my INSERT statement doesn't work and I can't find the error:/ Sry for my bad english, I am german.
"Fatal error: Call to a member function bind_param() on boolean in"
if (isset($_POST['registrieren']) && $_POST['name'] != "" && $_POST['password'] != "")
{
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privateKey = "???????????????????????????";
$response = file_get_contents($url . "?secret=" . $privateKey . "&response=" . $_POST['g-recaptcha-response'] . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) && $data->success == true)
{
$name = $_POST['name'];
$password = $_POST['password'];
$username_exists = $db->prepare("SELECT name from users WHERE name = ? ");
$username_exists->bind_param('s', $name);
$username_exists->execute();
if ($username_exists->num_rows) {
echo "<div class='fehler'>Name bereits vergeben!</div>";
} else {
$verschlüsseln = password_hash($password, PASSWORD_DEFAULT);
$insert = $db->prepare("INSERT INTO users (name, password) VALUES (?, ?)");
$insert->bind_param("ss", $name, $verschlüsseln);
$insert->execute();
$_SESSION['name'] = $name;
$_SESSION['password'] = $password;
header("Location: http://localhost/data/login/me.php");
}
} else {
echo "<div class='fehler'>Captcha-Check failed!</div>";
}
}
The error suggests that the prepare statement has failed but it's not clear which one. The code below is not tested and I wonder whether the accent on the u might have caused issues (?) so I renamed that variable to $hash
<?php
if( !empty( $_POST['registrieren'] ) && !empty( $_POST['name'] ) && !empty( $_POST['password'] ) && !empty( $_POST['g-recaptcha-response'] ) ){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privateKey = "6LdBNScTAAAAALrn5__S9lfV3EuSFu9Si_gwWeus";
$response = file_get_contents( $url . "?secret=" . $privateKey . "&response=" . $_POST['g-recaptcha-response'] . "&remoteip=" . $_SERVER['REMOTE_ADDR'] );
$data = json_decode( $response );
if( isset( $data->success ) && $data->success == true ) {
$name = $_POST['name'];
$password = $_POST['password'];
$stmt = $db->prepare("SELECT `name` from `users` WHERE `name` = ?;");
if( !$stmt ){
exit('Error preparing sql select statement');
}
$stmt->bind_param( 's', $name );
$stmt->execute();
if ( $stmt->num_rows ) {
echo "<div class='fehler'>Name bereits vergeben!</div>";
} else {
/* release results from previous cmd */
$stmt->free_result();
/* Is it possible that the accent on the 'u' caused problems? */
$hash = password_hash( $password, PASSWORD_DEFAULT );
$stmt = $db->prepare( "INSERT INTO `users` (`name`, `password`) VALUES (?, ?);" );
if( !$stmt ){
exit('Error preparing sql insert statement');
}
$stmt->bind_param( "ss", $name, $hash );
$stmt->execute();
/* again, free the results */
$stmt->free_result();
/* do you really want to store a password in a session variable? */
$_SESSION['name'] = $name;
$_SESSION['password'] = $password;
header("Location: http://localhost/data/login/me.php");
}
} else {
echo "<div class='fehler'>Captcha-Check failed!</div>";
}
}
?>