unable to insert into database in laravel - php

i have below code in Laravel Model (class) to insert into database ,
but i get error: "
PDOException in ... SQLSTATE[42000] :syntax error ...
public function Add_new($Desc, $Cat_Name, $Loc_Name, $Loc_Des, $Comment, $Ven_Name)
{
$pdo = DB::connection()->getPdo();
$stmt = $pdo->prepare('
INSERT INTO itinv_category (name)
VALUES (:Cat_Name);
INSERT INTO itinv_location (name, Description)
VALUES (:Loc_Name,:Loc_Des);
INSERT INTO itinv_comment (text)
VALUES (:Comment);
INSERT INTO itinv_vendor (name)
VALUES (:Ven_Name);
SET #id1 = (SELECT MAX(id) FROM itinv_vendor);
SET #id2 = (SELECT MAX(id) FROM itinv_comment);
SET #id3 = (SELECT MAX(id) FROM itinv_location);
SET #id4 = (SELECT MAX(id) FROM itinv_category);
INSERT INTO itinv_inventory (category_id,location_id,vendor_id,comment_id,Description)
VALUES (#id4,#id3,#id1,#id2,:Desc);
');
$stmt->bindValue('Cat_Name', $Cat_Name);
$stmt->bindValue('Loc_Name', $Loc_Name);
$stmt->bindValue('Loc_Des', $Loc_Des);
$stmt->bindValue('Comment', $Comment);
$stmt->bindValue('Desc', $Desc);
$stmt->execute();
}
}

You are missing the Ven_Name:
$stmt->bindValue('Ven_Name', $Ven_Name);

i solved the problem , it was about ' pdo ' which can not operate multiple Mysql queries , we need to execute each query seperatley like below :
public function Add_new($Desc, $Cat_Name, $Loc_Name, $Loc_Des, $Comment, $Ven_Name)
{
// var_dump($Desc);
$stmt1 = ' INSERT INTO itinv_category (name)
VALUES (\'' . $Cat_Name . '\')';
$stmt2 = '
INSERT INTO itinv_location (name, Description)
VALUES (\'' . $Loc_Name . '\', \'' . $Loc_Des . '\')';
$stmt3 = 'INSERT INTO itinv_comment (text)
VALUES (\'' . $Comment . '\')';
$stmt4 = ' INSERT INTO itinv_vendor (name)
VALUES (\'' . $Ven_Name . '\')';
$stmt5 = 'SELECT MAX(id) AS id FROM itinv_vendor';
$stmt6 = 'SELECT MAX(id) AS id FROM itinv_comment';
$stmt7 = 'SELECT MAX(id) AS id FROM itinv_location';
$stmt8 = 'SELECT MAX(id) AS id FROM itinv_category';
$pdo = \DB::connection()->getPdo();
$stmt = $pdo->prepare($stmt1);
$stmt->execute();
$stmt = $pdo->prepare($stmt2);
$stmt->execute();
$stmt = $pdo->prepare($stmt3);
$stmt->execute();
$stmt = $pdo->prepare($stmt4);
$stmt->execute();
$stmt = $pdo->prepare($stmt5);
$stmt->setFetchMode(\PDO::FETCH_ASSOC);
$stmt->execute();
$arr = $stmt->fetchAll();
$Ven_ID = $arr['0']['id'];
$stmt = $pdo->prepare($stmt6);
$stmt->setFetchMode(\PDO::FETCH_ASSOC);
$stmt->execute();
$arr = $stmt->fetchAll();
$Comment_ID = $arr['0']['id'];
$stmt = $pdo->prepare($stmt7);
$stmt->setFetchMode(\PDO::FETCH_ASSOC);
$stmt->execute();
$arr = $stmt->fetchAll();
$Loc_ID = $arr['0']['id'];
$stmt = $pdo->prepare($stmt8);
$stmt->setFetchMode(\PDO::FETCH_ASSOC);
$stmt->execute();
$arr = $stmt->fetchAll();
$Cat_ID = $arr['0']['id'];
$stmt = $pdo->prepare('INSERT INTO itinv_inventory (category_id,location_id,vendor_id,comment_id,Description)
VALUES (:Cat_ID,:Loc_ID,:Ven_ID,:Comment_ID,:Desc)');
$stmt->bindValue('Cat_ID', $Cat_ID);
$stmt->bindValue('Loc_ID', $Loc_ID);
$stmt->bindValue('Comment_ID', $Comment_ID);
$stmt->bindValue('Ven_ID', $Ven_ID);
$stmt->bindValue('Desc', $Desc);
$stmt->execute();
}
}

Related

MySQL INSERT INTO worked in php myadmin but not in an php code

i work on an simple mutiple INSERT INTO that works fine in phpmyadmin.
When i execute the same code in php i recieve an error:
1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO fm_support_cont (sup_id_cont, mail, phone) VALUES ((SELECT s' at line 2
Thank you :-)
INSERT INTO `fm_support` (`name`, `surname`, `role_id_sup`) VALUES (?,?,?);
INSERT INTO `fm_support_cont` (`sup_id_cont`, `mail`, `phone`) VALUES ((SELECT sup_id FROM `fm_support` WHERE name = ? AND surname = ?),?,?);
INSERT INTO `fm_user` (`user`, `isadmin`, `user_data`) VALUES (?,?,(SELECT sup_id FROM `fm_support` WHERE name =? AND surname = ?));
The PHP CODE i use:
private function includeNewUser()
{
$data = $this->d;
$newName = $data[0];
$newSurname = $data[1];
$newRole = $data[2];
$newEmail = $data[3];
$newPhone = $data[4];
$newUser = $data[5];
$newIsadmin = $data[6];
$newApw = password_hash($data[7], PASSWORD_DEFAULT);
$SQL = " INSERT INTO `fm_support` (`name`, `surname`, `role_id_sup`) VALUES (?,?,?);
INSERT INTO `fm_support_cont` (`sup_id_cont`, `mail`, `phone`) VALUES ((SELECT sup_id FROM `fm_support` WHERE name = ? AND surname = ?),?,?);
INSERT INTO `fm_user` (`user`, `isadmin`, `user_data`) VALUES (?,?,(SELECT sup_id FROM `fm_support` WHERE name =? AND surname = ?));";
$conn = $this->connect();
if($stmt = $conn->prepare($SQL)) {
$stmt->bind_param("ssisssssiss", $newName, $newSurname, $newRole, $newName, $newSurname, $newEmail, $newPhone, $newUser, $newIsadmin, $newName, $newSurname);
$stmt->execute();
//$result = $stmt->get_result();
//$insertResult = $result->fetch_assoc();
if($newIsadmin == 1)
{
$stmt = $db->prepare("INSERT INTO `fm_apw`(`pw_for`, `pw`) VALUES ((SELECT id FROM fm_user WHERE user = ?), ?);");
$stmt->bind_param("ss",$newUser, $newApw);
$stmt->execute();
}
$result = true;
}
else
{
$result = $conn->errno . ' ' . $conn->error;
echo $result; // 1054 Unknown column 'foo' in 'field list'
//$result = false;
}
return $result;
}
}

Join generate Unique ID in username INSERT POST

I have a function to insert username in database, while the database generate unique_id column.
how do i make username get additional suffix, from unique_id column
so it will be looks like this.
username+unique_id
example:John92749
so Input Post Field will add suffix from this column.
below are my function :
//Create user
function addUser($username, $reference_user_id, $user_ip_addr) {
global $conn;
$unique_id = mt_rand(10000,99999);
$stmt = $conn->prepare("SELECT p.id FROM plans p where is_default = 1");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$res = $stmt->fetch();
$stmt = $conn->prepare("INSERT into users (username, plan_id, reference_user_id, ip_addr, unique_id)
VALUES (:un, :pid, :ref_id, :ip_addr, :unique_id)");
$stmt->bindParam(':un', $username);
$stmt->bindParam(':pid', $res['id']);
$stmt->bindParam(':ref_id', $reference_user_id);
$stmt->bindParam(':ip_addr', $user_ip_addr);
$stmt->bindParam(':unique_id', $unique_id);
$stmt->execute();
$uid = $conn->lastInsertId();
$stmt = $conn->prepare("INSERT into user_plan_history (user_id, plan_id,status,created_at) VALUES (:uid, :pid,'active',:date)");
$stmt->bindParam(':date', date('Y-m-d H:i:s'));
$stmt->bindParam(':uid', $uid);
$stmt->bindParam(':pid', $res['id']);
$stmt->execute();
}
You have to merge two variable
like
$uname = $username.''.$unique_id;
Then your code look like :
//Create user
function addUser($username, $reference_user_id, $user_ip_addr) {
global $conn;
$unique_id = mt_rand(10000,99999);
$uname = $username.''.$unique_id;
$stmt = $conn->prepare("SELECT p.id FROM plans p where is_default = 1");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$res = $stmt->fetch();
$stmt = $conn->prepare("INSERT into users (username, plan_id, reference_user_id, ip_addr, unique_id)
VALUES (:un, :pid, :ref_id, :ip_addr, :unique_id)");
$stmt->bindParam(':un', $uname);
$stmt->bindParam(':pid', $res['id']);
$stmt->bindParam(':ref_id', $reference_user_id);
$stmt->bindParam(':ip_addr', $user_ip_addr);
$stmt->bindParam(':unique_id', $unique_id);
$stmt->execute();
$uid = $conn->lastInsertId();
$stmt = $conn->prepare("INSERT into user_plan_history (user_id, plan_id,status,created_at) VALUES (:uid, :pid,'active',:date)");
$stmt->bindParam(':date', date('Y-m-d H:i:s'));
$stmt->bindParam(':uid', $uid);
$stmt->bindParam(':pid', $res['id']);
$stmt->execute();
}
this will give output : John92749
Try this
$username = $username.$unique_id; //Append username and unique_id

PHP Prepared statements inserting data into all but one table (MySQL)

I'm working on an inbox system. On the front end, it uses jQuery and Ajax so the page doesn't refresh. I've got that part handled. On the back end, there are 3 tables (for now) that get data inserted.
Here is a basic rundown of the relation structures:
conversations:
conversation_id int(11) primary key
conversation_subject varchar(128)
conversations_members:
conversation_id int(11)
user_id int(11)
conversation_last_view int(10)
conversation_deleted int(1)
conversations_messages:
message_id int(11) primary key
conversation_id int(11)
user_id int(11)
message_date timestamp
message_text text
There is an additional problem since the sender_id is always 0, but that will have to be for another question since it's off topic.
The problem lies in the conversations_members table. Everything else gets entered into the conversations and conversations_messages tables. Here is the PHP. The issue is the very last SQL query at the bottom:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include('../inc/connect.php');
if (!isset($_SESSION['username'])) {
session_start();
}
$recipient_username = "";
$sender_id = "";
$a = 0;
$b = 0;
if(isset($_POST['subject'], $_POST['msg_body']) && !empty($_POST['subject']) && !empty($_POST['msg_body'])) {
//get ID of sender
$sender_id_query = "SELECT id FROM `users` WHERE username = ?";
$stmt = $connection->prepare($sender_id_query);
$stmt->bind_param('s', $_SESSION['username']);
$stmt->execute();
$result = mysqli_query($connection, $sender_id_query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
//$row['id'] = $sender_id; //neither of these work
$sender_id = $connection->insert_id; //Always zero
}
}
$stmt->close();
//get username of recipient
$recipient_name_query = "SELECT * FROM `users`";
$result = mysqli_query($connection, $recipient_name_query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
$row['username'] = $recipient_username;
}
}
//define post variables
$msg_subject = $_POST['subject'];
$msg_body = $_POST['msg_body'];
$subject = $connection->real_escape_string(htmlentities($msg_subject));
$body = $connection->real_escape_string(htmlentities($msg_body));
$conversation_id = mysqli_insert_id($connection);
//GET RECIPIENT ID
$sql = "SELECT id FROM `users` WHERE username=?";
$stmt = $connection->prepare($sql);
$stmt->bind_param('s', $recipient_username);
$result = mysqli_query($connection, $sql);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$recipient_id = $row['id'];
}
}
$stmt->close();
//INSERT SUBJECT INTO CONVERSATIONS TABLE
$stmt = $connection->prepare("INSERT INTO `conversations` (conversation_subject) VALUES(?)");
$stmt->bind_param('s', $subject);
$stmt->execute();
$stmt->close();
//INSERT THE IDs AND TIMESTAMPS INTO MESSAGES TABLE
$stmt = $connection->prepare("INSERT INTO `conversations_messages` (conversation_id, user_id, message_date, message_text)
VALUES(?, ?, NOW(), ?)");
$stmt->bind_param('iis', $conversation_id, $sender_id, $body);
$stmt->execute();
$stmt->close();
/*
THE FOLLOWING DATA DOES NOT GET INSERTED.....
*/
//INSERT IDs, LAST_VIEWED, AND DELETED INTO MEMBERS TABLE
$stmt = $connection->prepare("INSERT INTO `conversations_members` (conversation_id, user_id, conversation_last_view, conversation_deleted)
VALUES (?, ?, ?, ?)");
$stmt->bind_param('iiii', $conversation_id, $recipient_id, $a, $b);
$stmt->execute();
$stmt->close();
}
I get no errors, and I'm not seeing any typos. Where did I go wrong?
Thanks to the suggestion of additional error checking, it led me to discover what was happening. I completely removed the while loops, and gave each $stmt variable it's own name since I discovered another error after removing the while loops. Every statement after the first was returning a FALSE value since the previous statement wasn't closed. This code works. I get no errors, and it inserts everything into the database as required.
$recipient_username = $_GET['username'];
$username = $_SESSION['username'];
$a = 0;
$b = 0;
//get ID of sender
$sender_id_query = "SELECT id FROM `users` WHERE username = ?";
$stmt = $connection->prepare($sender_id_query);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($sender_id);
$val = $stmt->fetch()[$sender_id];
$stmt->close();
//define post variables
$msg_subject = $_POST['subject'];
$msg_body = $_POST['msg_body'];
$subject = $connection->real_escape_string(htmlentities($msg_subject));
$body = $connection->real_escape_string(htmlentities($msg_body));
$conversation_id = mysqli_insert_id($connection);
//GET RECIPIENT ID
$recipient_id_query = "SELECT id FROM `users` WHERE username=?";
$stmt2 = $connection->prepare($recipient_id_query);
$stmt2->bind_param('s', $recipient_username);
$stmt2->execute();
$stmt2->bind_result($recipient_id);
$val_2 = $stmt2->fetch()[$recipient_id];
$stmt2->close();
//INSERT SUBJECT INTO CONVERSATIONS TABLE
$stmt3 = $connection->prepare("INSERT INTO `conversations` (conversation_subject) VALUES(?)");
$stmt3->bind_param('s', $subject);
$stmt3->execute();
$stmt3->close();
//INSERT THE IDs AND TIMESTAMPS INTO MESSAGES TABLE
$stmt4 = $connection->prepare("INSERT INTO `conversations_messages` (conversation_id, user_id, message_date, message_text)
VALUES(?, ?, NOW(), ?)");
$stmt4->bind_param('iis', $conversation_id, $sender_id, $body);
$stmt4->execute();
$stmt4->close();
//INSERT IDs, LAST_VIEWED, AND DELETED INTO MEMBERS TABLE
$stmt5 = $connection->prepare("INSERT INTO `conversations_members` (conversation_id, user_id, conversation_last_view, conversation_deleted)
VALUES (?, ?, ?, ?)");
$q = $stmt5->bind_param('iiii', $conversation_id, $recipient_id, $a, $b);
$stmt5->execute();
$stmt5->close();

Insert stmt with a Select and additional Params

Is it possible to have a "mixed" SQL Insert like the following?
I want to be able to get one value from another table (that needs a param) and then enter in 2 more params.
$sql = "INSERT INTO tblquestions (userID, questionText, questionAnswer) VALUES (
Select userID FROM tblusers WHERE userEmail = (?),?,?)";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'sss', $userEmail, $question, $answer);
$result = mysqli_stmt_execute($stmt);
if (!$result) {
throw new Exception($conn->error);
}
It is unnecessary. Just use insert . . . select:
INSERT INTO tblquestions(userID, questionText, questionAnswer)
Select userID, ?, ?
FROM tblusers
WHERE userEmail = (?);

Parameter binding fails where concatenation works

I am trying to execute the following sql from php using pdo: SELECT * FROM my_table WHERE name=?.
When I do this:
$sql = 'SELECT * FROM my__table WHERE name=?' ;
$stmt = $dbconn->prepare($sql);
$stmt->bindValue(1, $_POST['name'], PDO::PARAM_STR);
$stmt->execute();
I get an empty result set.
When I do this:
$sql = 'SELECT * FROM my__table WHERE name=\''.$_POST['name'].'\'' ;
$stmt = $dbconn->prepare($sql);
$stmt->execute();
I get the row that I need.
The column 'name' is a VARCHAR(32). This bug only happens with strings. When the bound parameter is an sql INTEGER everything works like it is supposed to.
I am using sqlite3, php 5.2.6 under Apache on Ubuntu.
Both of these should work:
Without using binding
$sql = "SELECT * FROM my__table WHERE name = ? " ;
$stmt = $dbconn->prepare($sql);
$stmt->execute(array($_POST['name']));
Using a named parameter
$sql = "SELECT * FROM my__table WHERE name = :name " ;
$stmt = $dbconn->prepare($sql);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$stmt->execute(array($_POST['name']));
What about this?
$sql = "SELECT * FROM my__table WHERE name='?'" ;
$stmt = $dbconn->prepare($sql);
$stmt->bindValue(1, $_POST['name'], PDO::PARAM_STR);
$stmt->execute();

Categories