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();
Related
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
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
I am trying to convert my mysqli database that was very vulnerable to PDO prepared statements. I think i almost got it since it actully inputs the registration data to the database but not to the other databases. So i think there must be some issues on those queries but i can't figure it out. Here below is my code.
<?php
session_start();
// DATABASE CONNECTION
$user = '****';
$pass = '****';
//CREATE CONNECTION
// $conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
$pdo = new PDO('mysql:host=localhost;dbname=****', $user, $pass);
// ASSIGN VARIABLE FROM FORM
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$password = password_hash($password, PASSWORD_BCRYPT);
// CHECK IF USER IS UNIQUE
$stmt = $pdo->prepare("SELECT username FROM users WHERE username = :name");
$stmt->bindParam(':name', $username);
$stmt->execute();
if ($stmt->rowCount() > 0) {
echo "That username already exist!";
} else {
//INSERT DATA INTO DATABASE
$sql = "INSERT INTO users ( username, password, email )
VALUES ( :username, :password, :email )";
$sql1 = "INSERT INTO stats (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
$sql2 = "INSERT INTO progression (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
$sql3 = "INSERT INTO powervalues (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
// EXECUTE AND PREPARE
$query = $pdo->prepare($sql);
$query1 = $pdo->prepare($sql1);
$query2 = $pdo->prepare($sql2);
$query3 = $pdo->prepare($sql3);
$result = $query->execute(array( ':username'=>$username, ':password'=>$password, ':email'=>$email ));
$result1 = $query1->execute(array( ':username'=>$username ));
$result2 = $query2->execute(array( ':username'=>$username ));
$result3 = $query3->execute(array( ':username'=>$username ));
//EXECUTE QUERY
if ($result && $result1 && $result2 && $result3) {
$_SESSION['Accountsucess'] = "Account has been added sucessfully.";
header("location: ../../index.php?page=index");
} else {
echo "Error database failure";
}
}
Instead of continually selecting various parts of information, once you have inserted the user in the users table, fetch the last insert ID and then use that in subsequent calls...
$sql = "INSERT INTO users ( username, password, email )
VALUES ( :username, :password, :email )";
$sql1 = "INSERT INTO stats (id, username)
VALUES (:id,:username)";
// EXECUTE AND PREPARE
$query = $pdo->prepare($sql);
$query1 = $pdo->prepare($sql1);
$result = $query->execute(array( ':username'=>$username, ':password'=>$password, ':email'=>$email ));
// Fetch id of new user
$id = $pdo->lastInsertId();
$result1 = $query1->execute(array( ':id' => $id, ':username'=>$username ));
Repeat this same logic for each of the other statements.
How do i add multiples columns in pdo for update? this is what I am trying to do but I need to update multiple $_POSTS['VARS];
$consulta = $conexao_pdo->prepare('UPDATE user SET nome = ? WHERE id = ?');
$consulta->bindParam(1, $variavel_com_nome);
$consulta->bindParam(2, $id);
if ($consulta->execute()) {
echo 'UPDATED';
}
What is it that is not working in your code? If you need to update multiple columns, you just need to include them in your update statement: update table1 set col1 = ?, col2 = ?, col3 = ? where id = ?; then assign parameter values for each one.
This is how I solved it
$sql = "UPDATE user SET name = :name,
surname = :surname
WHERE username = :username";
//db column and value
$stmt = $conexao_pdo->prepare($sql);
//where clause
$stmt->bindParam(':username', $username);
//add vars to db
$stmt->bindParam(':name', $var);
$stmt->bindParam(':surname', $var);
$stmt->execute();
I have this simple pre-sort database input thing, I've created this before, what I'm screwing up is the while aspect.
There are two different tables: a table that keeps track of keyword frequencies and a table for the entries themselves paired with the keyword.
What I'm doing is saving something by a keyword, I check if the keyword exists, if it does, I increment the count of that keyword and then proceed to add the entry to the entry database, if not I create a new entry of that keyword in the keyword table and set the count as 1, then add the entry to the entry database.
$query = "SELECT COUNT(*) FROM key WHERE key=?";
if($stmt = $link->prepare($query)){
$stmt->bind_param('s',$key);
$stmt->execute();
while ($row = $stmt->fetch_row()){
$count = $row[0];
}
// count comes out here
// echo $count;
if($count==0){
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss',$id,$poster,$key,$entry,$date);
$stmt->execute();
// insert new key
$stmt = mysqli_prepare($link, "INSERT INTO key VALUES (?,?,?)");
$stmt->bind_param('isi',$id,$key,$numtimes);
$stmt->execute();
} else {
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss',$id,$poster,$key,$entry,$date);
$stmt->execute();
// update key count
$stmt = mysqli_prepare($link, "UPDATE key SET numtimes=key+1 WHERE key=$key");
$stmt->bind_param('s',$key);
$stmt->execute();
}
}
<?php
$query = "SELECT COUNT(*) FROM key WHERE key=?";
if($stmt = $link->prepare($query)){
$stmt->bind_param('s', $key);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_row()){
$count = $row[0];
}
$stmt->close();
// count comes out here
// echo $count;
if($count == 0){
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss', $id, $poster, $key, $entry, $date);
$stmt->execute();
// insert new key
$stmt = mysqli_prepare($link, "INSERT INTO key VALUES (?,?,?)");
$stmt->bind_param('isi',$id,$key,$numtimes);
$stmt->execute();
$stmt->close();
} else {
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss',$id,$poster,$key,$entry,$date);
$stmt->execute();
// update key count
$stmt = mysqli_prepare($link, "UPDATE key SET numtimes=key+1 WHERE key=$key");
$stmt->bind_param('s',$key);
$stmt->execute();
$stmt->close();
}
}
?>
This should do the trick for you, you can't use fetch_row() directly on $stmt, that was your mistake.
There are two issues
first
while ($row = $stmt->fetch_row()){
$count = $row[0];
}
should be replaced by simply
$count = $stmt-rowCount()
You actually don't need the 'keys' table. Consider your DB schema again. The keys table is superfluous. The 'entry' table will suffice just update the entry table and you are good. All information can be obtained by querying the entry table rightly
I am trying to enter 3 different data to a mysql database 'pages'
The first 2 data is submitted to the database but the third 'dname' is not.
The $_SESSION['dname'] contains the value to be added to the column 'dname'
The php looks like:
if (isset($_POST['submit']))
{
$menulabel = $_POST['menulabel'];
$content = $_POST['content'];
$dname = $_SESSION['dname'];
$query = "INSERT INTO pages (menulabel, content, dname) VALUES (?, ?, ?)";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('sss', $menulabel, $content, $dname);
$statement->execute();
$statement->store_result();
if ($statement->error)
{
die('Database query failed: ' . $statement->error);
}
$creationWasSuccessful = $statement->affected_rows == 1 ? true : false;
if ($creationWasSuccessful)
{
header ("Location: index.php");
}
else
{
echo 'Failed';
}
}
The mysql table:
$query_pages = "CREATE TABLE IF NOT EXISTS pages (id INT NOT NULL AUTO_INCREMENT, menulabel VARCHAR(50), content TEXT, dname VARCHAR(50), PRIMARY KEY (id))";
$databaseConnection->query($query_pages);
The php successfully adds the 'menulabel' and 'content' to the table and continues leaving the 'dname' NULL.
Please help, this is my first time with php.
Here you go buddy. This should fix your issue. Instead of throwing the object into the params, utilize it in the query instead.
$menulabel = $_POST['menulabel'];
$content = $_POST['content'];
$dname = $_SESSION['dname'];
$query = "INSERT INTO pages (menulabel, content, dname) VALUES (?, ?, '$dname')";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('ss', $menulabel, $content);
$statement->execute();
$statement->store_result();