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
Related
This is my code:
function getUsers($connection ,$username) {
$sql = "SELECT * FROM users where username = ?";
$stmt = $connection->prepare($sql);
$stmt->bindParam("s", $username, PDO::PARAM_STR);
return $stmt->fetchAll();
}
$voornaam = "dave";
$users = getUsers($connection, $voornaam);
print_r($users);
When I open my webpage, I get an empty Array.
I checked, and there is a user with the username "dave" in my database.
This should work, however, it doesn't...
Anyone knows what I did wrong?
Thanks in advance.
First is, you have to execute it before using fetchAll():
$stmt->execute();
$result = $stmt->fetchAll();
This is the correct way:
$stmt = $connection->prepare('SELECT * FROM users where username = :username');
$stmt->bindParam(':username', $username);
If you want to user ? it will determine the order of ? in bindParam, use it like this:
$sql = "SELECT * FROM users where username = ?";
$stmt = $connection->prepare($sql);
$stmt->bindParam(1, $username, PDO::PARAM_STR);
More example:
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
Instead of using
$stmt->bindParam("s", $username, PDO::PARAM_STR);
you need to use
$stmt->bindParam(1, $username, PDO::PARAM_STR);
Check this link for details https://www.php.net/manual/en/pdostatement.bindparam
You need to check this Example #2 Execute a prepared statement with question mark placeholders
This is the correct way
$sql = "SELECT * FROM users where username = ?";
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $username, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetchAll();
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();
}
}
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();
Can some onw please explain what is wrong with this ... this worked completely fine with procedural php
function foo(){
$incomingtime = date('Y-m-d H:i:s', time());
$stmt = $db->stmt_init();
$id = "Abc123" ;
$u_id = 1;
$c_id = 1;
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('ssii', $incomingtime, $id, $u_id, $c_id);
$stmt->execute();
printf("Affected rows (UPDATE): %d\n", $db->affected_rows); // Always return 1
$stmt->close();
}
But nothing goes in the database.
Datatype in mysql db for indate is datetime
There's several issues with this code.
$stmt_4 is used before it's defined.
$u_id and $c_id are both defined then not used.
Trying to execute $stmt without supplying parameters.
$db is not defined.
$id is not defined.
If you are trying to convert working code to a function make sure that either the function gets these passed in as an argument, they are marked as global or the function creates/ retrieves them.
Check changing:
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('ssii', $incomingtime, $id, $u_id, $c_id);
$u_id = 1;
$c_id = 1;
$stmt->execute();
to:
$u_id = 1;
$c_id = 1;
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (CURRENT_TIMESTAMP, ?, ?, ?)"
$stmt = $db->prepare($query);
$stmt->execute(array($id, $u_id, $c_id));
NOTE: I deleted the parameter ssii because it's not considered in the query. It only expects 4 parameters.
i have a pdo block for inserting values into my table as follows
try{
$user = 'root';
$pass = null;
$pdo = new PDO('mysql:host=localhost; dbname=divebay', $user, $pass);
$name = $_POST['name'];
$desc = $_POST['description'];
$cond = $_POST['condGroup'];
$sprice = $_POST['sprice'];
$iprice = $_POST['iprice'];
$incprice = $_POST['incprice'];
$duration = $_POST['duration'];
$img = $_POST['img'];
$owner = $_SESSION['username'];
$valid = "set";
$stmt2 = $pdo->prepare("SELECT * FROM auction WHERE ID = :id");
$stmt2->bindParam(":id", $random, PDO::PARAM_INT);
while(isset($valid)){
$random = rand(100000,999999);
$stmt2->execute();
if(!$stmt2->fetch(PDO::FETCH_ASSOC)){
unset($valid);
}
}
$timestamp = time() + ($duration * 24 * 60 * 60);
$stmt = $pdo->prepare("INSERT INTO auction(ID, name, owner, holder, sprice, iprice, incprice, etime, img, condition, description)
VALUES (:id, :name, :owner, :holder, :sprice, :iprice, :incprice:, :etime, :img, :condition, :description");
$stmt->bindParam(':id', $random, PDO::PARAM_INT);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':owner', $owner, PDO::PARAM_STR);
$stmt->bindParam(':holder', $owner, PDO::PARAM_STR);
$stmt->bindParam(':iprice', $iprice, PDO::PARAM_STR);
$stmt->bindParam(':sprice', $sprice, PDO::PARAM_STR);
$stmt->bindParam(':incprice', $incprice, PDO::PARAM_STR);
$stmt->bindParam(':etime', $timestamp, PDO::PARAM_INT);
$stmt->bindParam(':img', $img, PDO::PARAM_STR);
$stmt->bindParam(':condition', $condition, PDO::PARAM_STR);
$stmt->bindParam(':description', $description, PDO::PARAM_STR);
if($stmt->execute()){
$worked ="yes";
}
}catch(PDOException $e){
echo $e->getMessage();
}
i cant tell why this statement wont execute, the $worked variable has not been set when it is the script is run. all database column names and datatypes have been checked correct as they are. ive never had a problem with a statement not executing until now. whats wrong? how do i go about debugging this?
If you setup the database connection with error mode exception PDO will throw an exception if something is wrong with your statement. I also see that you are using the MySQL driver for PDO. If you do this you should always disable emulated prepared statements. So I would write you connection as following (note that I have also set the encoding):
$pdo = new PDO('mysql:host=localhost; dbname=divebay;charset=utf8', $user, $pass);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Also see this post for more information about this.
Once you have done this you will see that your statement is wrong. You have one missing ) at the end of the statement:
$stmt = $pdo->prepare("INSERT INTO auction(ID, name, owner, holder, sprice, iprice, incprice, etime, img, condition, description)
VALUES (:id, :name, :owner, :holder, :sprice, :iprice, :incprice:, :etime, :img, :condition, :description)");
^
Modify this line:
$stmt = $pdo->prepare("INSERT INTO auction(ID, name, owner, holder, sprice, iprice, incprice, etime, img, condition, description)
VALUES (:id, :name, :owner, :holder, :sprice, :iprice, :incprice:, :etime, :img, :condition, :description");
To
$stmt = $pdo->prepare("INSERT INTO auction(ID, name, owner, holder, sprice, iprice, incprice, etime, img, condition, description)
VALUES (:id, :name, :owner, :holder, :sprice, :iprice, :incprice:, :etime, :img, :condition, :description)");
The difference is the ) at the end.
And tell me if it works now.