Why is this PHP while query not working? - php

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

Related

while loop inserting same value in table

I can't figure out what is wrong with my logic here. The first query returns four items ( I confirmed that). I want to insert these ids in another table. Four inserts occur but all with the first id only. What is wrong here?
$query = "SELECT id FROM table1 WHERE item IN (".$x.") ORDER by id";
$result = $mysqli->query($query);
$sqq = "INSERT INTO table2 (item1, item2, item3) VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($sqq);
while($row = $result->fetch_object()) {
$stmt->bind_param('ssi', $it1, $it2, $row);
$stmt->execute();
}
The function fetch_object() returns an object, but you're trying to use it as an integer. You should use $row->id to get the value.
while($row = $result->fetch_object()) {
$stmt->bind_param('ssi', $it1, $it2, $row->id);
$stmt->execute();
}

How to update two table with prepared statements?

I've run into some trouble trying to figure out how to update two mysql tables using prepared statements. The first table is updated with the new data but not the second. Can anyone tell me what I've got wrong? Thanks.
/Update Databases
$stmt = $db_conx->prepare('UPDATE tbl_users SET user_name=?, role=?, user_email= ?, company = ?, bio = ?, website = ? WHERE user_id=?');
$stmt->bind_param('sssssss',$user_name,$role,$user_email,$company,$bio,$website,$phone_no, $user_id);
$stmt->execute();
//Update second table
$stmt = $db_conx->prepare('UPDATE useroptions SET user_name=? WHERE user_id=?');
$stmt->bind_param('ss',$user_name,$user_id);
$stmt->execute();
//
if($stmt){
echo
'success";
}
else{ echo "An error occurred!"; }
You have a wrong number of argument in first query 7 ? 7 s but 8 $var ($phone_no )
//Update Databases
$stmt = $db_conx->prepare('UPDATE tbl_users SET user_name=?, role=?, user_email= ?, company = ?, bio = ?, website = ? WHERE user_id=?');
$stmt->bind_param('sssssss',$user_name,$role,$user_email,$company,$bio,$website,$phone_no, $user_id);
^^^^^^
$stmt->execute();
//Update second table
$stmt = $db_conx->prepare('UPDATE useroptions SET user_name=? WHERE user_id=?');
$stmt->bind_param('ss',$user_name,$user_id);
$stmt->execute();
//

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();

mysqli_num_rows not working in MySQLi with PHP

I would like to check if there already exists a record before inserting a new one. But it doesn't work so far, here is the script:
<?php
session_start();
$uname = $_SESSION['username'];
$friend = $_GET["newfriend"];
$db = new mysqli("localhost", "...", "....", "...");
if($db->connect_errno > 0){
die("Unable to connect to database: " . $db->connect_error);
}
$checkexist = $db->query("SELECT * FROM friends WHERE (username_own='$uname', username='$friend')");
//create a prepared statement
$stmt = $db->prepare("INSERT INTO friends (`username_own`, `username`) VALUES (?,?)");
//bind the username and message
$stmt->bind_param('ss', $uname, $friend);
if ($checkexist->mysqli_num_rows == 0) {
//run the query to insert the row
$stmt->execute();
}
Try something like this:
<?php
/* Check if user exists */
$query = "SELECT count(1) FROM friends WHERE username_own=? AND username=?";
if($stmt = $db->prepare($query)){
$stmt->bind_param('ss', $uname, $friend);
$stmt->execute();
$stmt->bind_result($count_rows);
$stmt->fetch();
$stmt->close();
}else die("Failed to prepare");
/* If user doesn't exists, insert */
if($count_row == 0){
$query = "INSERT INTO friends (`username_own`, `username`) VALUES (?,?)";
if($stmt = $db->prepare($query)){
$stmt->bind_param('ss', $uname, $friend);
$stmt->execute();
$stmt->close();
}else die("Failed to prepare!");
}
Try this:
//create a prepared statement
$stmt = $db->prepare("INSERT INTO friends (`username_own`, `username`) VALUES (?,?)");
//bind the username and message
$stmt->bind_param('ss', $uname, $friend);
if ($checkexist->mysqli_num_rows == 0 || $checkexist->mysqli_num_rows <> 0) {
//run the query to insert the row
$stmt->execute();
}
$checkexist->mysqli_num_rows is wrong. It's just
$checkexist->num_rows
or you can use
mysqli_num_rows($checkexist)
Hope this helps.
Replace most of your code with a simple INSERT IGNORE ... or INSERT ... ON DUPLICATE KEY UPDATE ....
The latter lets you change columns if the record already exists (based on any PRIMARY or UNIQUE key(s)).

How do I get the ID of an inserted row?

I have this following example query, which works - I CAN insert values into my MySQL table, which also includes an unique id column. I want to get the id from the inserted row, after I execute the query. However what I get is 0 every time ($gotId=0).
What am I doing wrong?
$stmt = $conn->prepare("INSERT INTO ....... ");
$stmt-> bind_param("ss", ....);
$stmt->execute();
$gotId = $conn->insert_id;
Full query:
$conn = $db->connect();
$stmt = $conn->prepare("INSERT INTO table(value1, value2) VALUES(?, ?)");
$stmt-> bind_param("ss", $value1, $value2);
$stmt->execute();
$gotId = $conn->insert_id;
After calling the execute() method on the PreparedStatement, the id of the insert row will be in the insert_id attribute Only read it.
$stmt->execute();
$gotId = $stmt->insert_id;
Taken from here
$query = "INSERT INTO .......";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
More Info

Categories