INSERT INTO relational database isn't working with php code - php

The code I have for the function trying to insert the data into the table is
function registerDiet(){
global $connect, $meat, $seafood, $salad, $name, $username, $age, $email, $password, $hash;
$statement = mysqli_prepare($connect, "SELECT user_id FROM User WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colUserID);
$statement = mysqli_prepare($connect, "INSERT INTO Diet (user_id, meat, seafood, salad) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "iiii", $colUserID, $meat, $seafood, $salad);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
}
The function is called towards the end of the code.
user_id is the primary key in the User table and a foreign key in the Diet table, the relationship has been configured and it works fine when using phpMyAdmin. Meat, seafood and salad field types are all boolean (tinyint) in the database table.
For example when I use
INSERT INTO `Diet` (`user_id`, `meat`, `seafood`, `salad`) VALUES ('46', '0', '0', '0');
in phpMyAdmin it works, anyone able to advise?

You have to close the first statement before opening another one.
function registerDiet(){
global $connect, $meat, $seafood, $salad, $name, $username, $age, $email, $password, $hash;
$statement = mysqli_prepare($connect, "SELECT user_id FROM User WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colUserID);
mysqli_stmt_close($statement);
$statement = mysqli_prepare($connect, "INSERT INTO Diet (user_id, meat, seafood, salad) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "iiii", $colUserID, $meat, $seafood, $salad);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
}

Related

all works but warning show up after doing the function

I have this code:
<link rel="stylesheet"href="includes/css/bootstrap.min.css"><?php
require_once "class.php";
$conn = new db_class();
if(ISSET($_POST['signup'])){
$username = $_POST['username'];
$password = sha1($_POST['password']);
$confpassword = sha1($_POST['confpassword']);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$conn->save($username, $password,$confpassword, $firstname, $lastname);
} ?>
and this is the function :
public function save($username, $password,$confpassword, $firstname, $lastname){
$stmt = $this->conn->prepare("SELECT * FROM `user` WHERE `username` = '$username'") or die($this->conn->error);
if($stmt->execute()){
$result = $stmt->get_result();
if($password!=$confpassword){
echo "<div class=\"alert alert-danger\"><strong>password does not match</strong></div>";
}else
if( $result->num_rows == 0){
$stmt1 = $this->conn->prepare("INSERT INTO `user` (username, password, confirmPass, firstname, lastname) VALUES('$username', '$password','$confpassword', '$firstname', '$lastname')") or die($this->conn->error);
$stmt1->bind_param("s", $username, $password, $confpassword, $firstname, $lastname);
$stmt1->execute();
everything work great except this warning:
Warning: mysqli_stmt::bind_param(): Number of elements in type
definition string doesn't match number of bind variables in C:\Program
Files
(x86)\EasyPHP-DevServer-14.1VC11\data\localweb\segments\class.php on
line 214
any idea? I tried to add more "s" in here:
$stmt1->bind_param("s", $username, $password, $confpassword, $firstname, $lastname);
And still have the same warning. Any ideas?
When using prepared statements, you must use placeholders. Without them, not only would you get unecessary fatal erros, but you are defeating the use of prepared statements.
You are binding 5 variables, therefore you need 5 placeholders to bind them.
$stmt1 = $this->conn->prepare("INSERT INTO `user` (username, password, confirmPass, firstname, lastname) VALUES(?, ?,?, ?, ?)") or die($this->conn->error);
$stmt1->bind_param("sssss", $username, $password, $confpassword, $firstname, $lastname);
$stmt1->execute();
This is wrong
$stmt1 = $this->conn->prepare("INSERT INTO `user` (username, password, confirmPass, firstname, lastname) VALUES('$username', '$password','$confpassword', '$firstname', '$lastname')") or die($this->conn->error);
You need to have placeholders that you will bind not variables above
this is what you need:
$stmt1 = $this->conn->prepare("INSERT INTO `user` (username, password, confirmPass, firstname, lastname) VALUES(?,?,?,?,?)") or die($this->conn->error);
$stmt1->bind_param("sssss", $username, $password, $confpassword, $firstname, $lastname);
$stmt1->execute();
Update :
this or die($this->conn->error); is somehow useless where you have put it as the query does not get executed, in that line you are just preparing, you need to check success/fail after execute()
therefore should be like :
<?php
$stmt1 = $this->conn->prepare("INSERT INTO `user` (username, password, confirmPass, firstname, lastname) VALUES(?,?,?,?,?)");
$stmt1->bind_param("sssss", $username, $password, $confpassword, $firstname, $lastname);
$stmt1->execute();
if(!$stmt1){
die($this->conn->error);
}
?>

INSERT no Result Value

I'm trying to insert some value into my database, but I got no result, but the code got no error, and the result label said it is succeed. My database connection working. How to check the issue here, I confused.
My Code Here
// insert new data to menu table
$sql_query = "INSERT INTO tbl_jadwal (Nama_Lokasi, Category_ID, Longitude, Latitude, Phone, Email, Menu_image, Description)
VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
$upload_image = 'upload/images/' . $menu_image;
$stmt = $connect->stmt_init();
if ($stmt->prepare($sql_query))
{
// Bind your variables to replace the ?s
$stmt->bind_param('sssssss',
$nama_lokasi,
$category_ID,
$longitude,
$latitude,
$phone,
$email,
$upload_image,
$description
);
// Execute query
$stmt->execute();
// store result
$result = $stmt->store_result();
$stmt->close();
}
This should do, you were missing one s in the param string
$stmt->bind_param('ssssssss',
$nama_lokasi,
$category_ID,
$longitude,
$latitude,
$phone,
$email,
$upload_image,
$description
And you have way too much code. Only a very little part of it is relevant

What to put in a MySQL auto-increment primary key field when inserting a row?

I'm new to PHP and I'm having a little trouble setting up my code to auto increment IDs for SQL. I'm aware that the method that I am attempting isn't a very good approach and know about the risks of race conditions etc. This will be temporary until I sort the rest of my code out properly.
Could somebody please tell me what I am doing wrong here? Or help me to get valid code?
My Class:
<?php
$user = 'root';
$pass = '';
$db = 'testuser';
$con=mysqli_connect('localhost', $user, $pass, $db) or die('Unable to connect');
$data = json_decode(trim(key($_POST), '[]'), true);
$email = $data['email'];
$name = $data['name'];
$shortDes = $data['shortDes'];
$longDes = $data['longDes'];
$max = mysqli_prepare($con, 'SELECT MAX(society_id) FROM society');
$society_id = $max + 1;
$statement = mysqli_prepare($con, 'INSERT INTO society(society_id, name, email, short_des, long_des) VALUES (?, ?, ?, ?, ?)');
mysqli_stmt_bind_param($statement, 'issss', $societyId, $name, $email, $shortDes, $longDes);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_close($statement);
mysqli_close($con);
?>
Focusing on the following snippet:
$max = mysqli_prepare($con, 'SELECT MAX(society_id) FROM society');
$society_id = $max + 1;
$statement = mysqli_prepare($con, 'INSERT INTO society(society_id, name, email, short_des, long_des) VALUES (?, ?, ?, ?, ?)');
mysqli_stmt_bind_param($statement, 'issss', $societyId, $name, $email, $shortDes, $longDes);
Just needed to remove the value for the auto incremented field altogether.

Mysqli prepared statements register

Okay I have one question. I need to check if the user already exists but the question is now what I need to type in the if() I can't fetch because I have closed but if I didn't close i got an error because there can't run 2 statements. So I think if there are someone who can help me? I have the rest code but I only give the code here.
Here is my code:
$result = $mysqli->prepare("SELECT username FROM user WHERE username=?");
$result->bind_param("s", $username);
$result->execute();
$result->bind_result($username);
$result->close();
if (){
$register = $mysqli->prepare("INSERT INTO user
(username, password, email, rr, rank)
VALUES (?, ?, ?, ?, ?)");
$register->bind_param("sssii", $username, $kode, $email, $rr, $rank);
$register->execute();
$register->close();
} else {
echo "User already exists!";
}
UPDATED: more logical statement
$result = $mysqli->prepare("SELECT username FROM user WHERE username=?");
$result->bind_param("s", $username);
$result->execute();
$found = $result->fetch();
$result->close();
if ($found){
echo "User already exists!";
} else {
$register = $mysqli->prepare("INSERT INTO user
(username, password, email, rr, rank)
VALUES (?, ?, ?, ?, ?)");
$register->bind_param("sssii", $username, $kode, $email, $rr, $rank);
$register->execute();
$register->close();
}

Proper way to pass query data to methods?

I have a User class and I'm wondering what would be the "most recommended" way to handle insertions?
Option 1: Use an existing object
// insert a new user and return the user id
public function insert() {
$sql = "INSERT INTO users (username, password, email, avatar, subscribe, created, last_login, valid) VALUES
(?, ?, ?, ?, ?, ?, ?, ?)";
$sth = $this->db->prepare($sql);
$sth->bindParam(1, $this->username, PDO::PARAM_STR);
$sth->bindParam(2, $this->password, PDO::PARAM_STR);
$sth->bindParam(3, $this->email, PDO::PARAM_STR);
$sth->bindParam(4, $this->avatar, PDO::PARAM_STR);
$sth->bindParam(5, $this->subscribe, PDO::PARAM_STR);
$sth->bindParam(6, $this->created, PDO::PARAM_STR);
$sth->bindParam(7, $this->last_login, PDO::PARAM_STR);
$sth->bindParam(8, $this->valid, PDO::PARAM_STR);
$sth->execute();
return $this->db->lastInsertId();
}
Option 2: Pass the information in as an array
// insert a new user and return the user id
public function insert(array $fields = array()) {
if(!empty($fields)) {
$sql = "INSERT INTO users (username, password, email, avatar, subscribe, created, last_login, valid) VALUES
(:username, :password, :email, :avatar, :subscribe, :created, :last_login, :valid)";
$sth = $this->db->prepare($sql);
$sth->execute($fields);
return $this->db->lastInsertId();
}
}
Another option? Does it make any difference?
Both ways are okay but personally I suggest second option

Categories