I am trying to make a messaging system in PHP in a dinky little app I'm making in android. I've gotten it mostly sorted out but there Is 1 problem I cant seem to fix. in my messaging system I want to display all the conversations the user has with other users along with the last text sent or received like on most messaging systems. the problem I am having is that the PHP script I made to get and displays all the conversation displays the last message for one user over and over again, for all the conversation the user has ongoing. see below
this is what my message table looks like, note it is supposed to get and display only the last text sent or recived, it does this but it only for 1 user but it displays it for both. if I had 3 or more texts from or to peter it would look the same but if I messaged another user it would display 3 texts
here is my code.
<?php
$pdo = new PDO("mysql:host=localhost;dbname=basicbook;charset=utf8mb4", 'root', '', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
require_once "basicbookconfig.php";
error_reporting(E_ALL);
ini_set('display_errors', 1);
$conn->set_charset('utf8mb4'); // always set the charset
if($_SERVER["REQUEST_METHOD"] == "POST") {
$f = file_get_contents('php://input');
$jsonobj = stripslashes($f);
$obj = json_decode($jsonobj);
$email = $obj[0];
// step 1 get id from email
$sql0 = "SELECT `id` FROM `users` WHERE email = ?";
$stmt0 = $conn->prepare($sql0);
$stmt0->bind_param("s", $email);
$stmt0->execute();
$stmt0->store_result();
if($stmt0->num_rows == 1) {
$stmt0->bind_result($id);
$stmt0->fetch();
// step 2 get chats off all people with that id
$stmt = $pdo->prepare("SELECT `person1`, `person2` FROM `chats` WHERE `person1` = ? or `person2` = ?");
$stmt->execute([$id,$id]);
$return22 = array();
while ($row = $stmt->fetch()) {
$person1 = $row["person1"];
$person2 = $row["person2"];
// echo $person1;
// echo $person2;
// echo "here";
// I expect it to do this twice
$stmt2 = $pdo->prepare("SELECT `message_id`, `user_to`, `user_from`, `message` FROM `messages` WHERE `user_to` = ? or ? and `user_from` = ? or ? ORDER BY message_id DESC LIMIT 1");
$stmt2->execute([$person1,$person2, $person1,$person2]);
while ($results = $stmt2->fetch()) {
$message_id = $results["message_id"];
$user_to = $results["user_to"];
$user_from = $results["user_from"];
$message = $results["message"];
if ($user_to == $id) {
$friend = $user_from;
} elseif ($user_from == $id) {
$friend = $user_to;
} else {
echo "there is a problem1";
}
$sql3 = "SELECT `name` FROM `users` WHERE `id` = ?";
$stmt3 = $conn->prepare($sql3);
$stmt3->bind_param("s", $friend);
$stmt3->execute();
$stmt3->store_result();
$stmt3->bind_result($name);
$stmt3->fetch();
$return22[] = array('message_id'=>$message_id, 'otherperson'=>$name, 'message'=>$message);
}
$b = array("my_messages" => $return22);
}
echo json_encode($b);
}
}
I have been trying varius fixes for a while now. anyways I hope it makes sense what I am trying to do. thank you and have a nice day, if you have any questions please ask.
Related
I am new in PHP and trying to build one API which provide me json response of required data. There one table called user and I need email, username and user_type from it. I have coded like below for do it
$result = array();
$users = getOnlineUsers($conn);
$userinfo['email'] = $users['email'];
$userinfo['username'] = $users['username'];
$userinfo['user_type'] = $users['user_type'];
$result['status'] ="success";
$result['userData'] = $userinfo;
And function is like below
function getOnlineUsers($conn)
{
$q = $conn->prepare("SELECT * FROM table_users WHERE online_status = 1");
// $q->bind_param("s", $email);
$q->execute();
$result = $q->store_result();
$metaResults = $q->result_metadata();
$fields = $metaResults->fetch_fields();
$statementParams='';
foreach($fields as $field){
if(empty($statementParams)){
$statementParams.="\$column['".$field->name."']";
}else{
$statementParams.=", \$column['".$field->name."']";
}
}
$statment="\$q->bind_result($statementParams);";
eval($statment);
$q->fetch();
return $column;
}
Its working fine but giving me only one row in response. I want get all row instead of one. I am getting response like this
{"status":"success","userData":{"email":"abc#gmail.com","username":"rajrathodbvn","user_type":0}}
Let me know if someone can help me for solve my issue.
Thanks
That's a lot of code for something so simple. Select the columns you want:
function getOnlineUsers($conn) {
$q = $conn->prepare("SELECT email, username, user_type
FROM table_users
WHERE online_status = 1");
$q->execute();
return $q->fetchAll(PDO::FETCH_ASSOC);
}
Then assign:
$result['status'] = 'success';
$result['userData'] = getOnlineUsers($conn);
Or:
$result = ['status' => 'success', 'userData' => getOnlineUsers($conn)];
/*mysql table admin
id=1, user_name = mike
id=2, user_name = sam*/
$user_name_query = mysql_query("select id, user_name from admin");
$user_name_array = array();
while ($row = mysql_fetch_array($user_name_query)) {
$user_name_array[] = array('user' => $row['user_name']);
}
foreach($user_name_array as $key => $record){
$record_values .= "{$record['user']},";
}
$record_values = substr($record_values, 0, -1);
// $record_values is: mike,sam
$userThatHaveThePermission = array($record_values);
if (in_array(mike, $userThatHaveThePermission)){
echo "do something"
}
my question is about the values of variable $record_values this variable not working in: $userThatHaveThePermission = array($record_values);
If I add the user names(mike,sam) to $userThatHaveThePermission = array(mike,sam); everything working fine, WHY? did I miss something.
I think you are beginner in php-mysql. I would refactor your code for you.
$user_name_query = mysql_query("select id, user_name from admin");
$user_name_array = [];
while ($row = mysql_fetch_array($user_name_query)) {
$user_name_array[] = $row['user_name'];
}
$userThatHaveThePermission = $user_name_array;
if (in_array('mike', $userThatHaveThePermission)){
echo "do something";
}
But take advice of the people commenting on your status. Do not use mysql_query. Use some framework.
im using php to insert into the review table.ive given the variables $email, $starcount, $bookid fixed values for now just to test the file. the $res query checks to see if there is a row with that book id and email in it. if theres not The $sql query inserts it, and then the $nex query loops through taking any starcount columns where the book column = $book.
if i change the the email at the top of the file it should insert into the new info database and pull out the new and existing starcount, but it does not post, it just returns the already existing starcount. i dont understand why its not working .... im using the array to return to my file.
<?php
mysql_connect("localhost","root","");
mysql_select_db("FunReads");
$email = "sd";
$starcount = "2";
$bookid = "5";
$res = mysql_query("SELECT * FROM Review WHERE book_id='$bookid' AND user_email='$email'");
if (mysql_num_rows($res) != 0) {
$array[]= array("starcount" => "already entered");
} else {
$sql = mysql_query("INSERT INTO Review(book_id,starcount,user_email) values('.$bookid.','.$starcount.','.$email')");
$nex = mysql_query("SELECT * FROM Review WHERE book_id='$bookid'");
while($row = mysql_fetch_array($nex)){
$star = $row["starcount"];
$array[] = array("starcount" => $star);
}
}
echo json_encode($array);
//echo "[{"name":"n1","city":"NY"},{"name":"n2","city":"Paris"}, ...]
?>
It seems to me "book_id" in "Review" table is primary key, as you have tried to add it multiple time, system shows the error duplicate key. Check the error & post it. Also check whether insert query is working or not.
you should not pass the primary key value manually
try this it will helps you
<?php
mysql_connect("localhost","root","");
mysql_select_db("FunReads");
$starcount="2";
$email = "vinodh#gmail.com";
$res=mysql_query("SELECT * FROM Review WHERE email ='$email'");
if(mysql_num_rows($res)!=0){
$array[]= array("starcount" => "already entered");
}else{
$sql=mysql_query("INSERT INTO Review (starcount,email) values('.$starcount.','.$email')");
$nex=mysql_query("SELECT * FROM Review WHERE email='$email'");
while($row=mysql_fetch_array($nex)){
$star = $row["starcount"];
$array[] = array("starcount" => $star);
}
}
echo json_encode($array);
?>
I just updated your code and it is working fine for me.
<?php
mysql_connect("localhost","user","");
mysql_select_db("xyz");
$email = "hari#gmail.com";
$starcount = "2";
$bookid = "5";
$sql = "SELECT * FROM review WHERE book_id='$bookid' AND user_email='$email'";
$res = mysql_query($sql);
if (mysql_num_rows($res) != 0) {
$array[]= array("starcount" => "already entered");
} else {
$sql = "INSERT INTO review(book_id,starcount,user_email) values('$bookid','$starcount','$email')";
$sql = mysql_query($sql);
$nex = mysql_query("SELECT * FROM review WHERE book_id='$bookid'");
while($row = mysql_fetch_array($nex)){
$star = $row["starcount"];
$array[] = array("starcount" => $star);
}
}
echo json_encode($array);
sample output :
[{"starcount":"2"},{"starcount":"3"},{"starcount":"1"},{"starcount":"2"},{"starcount":"1"}]
I updated the insert query, please try to update the same and test.
i have a problem on my project im currently working on and
this is my Email controller
i want to get the id of an email registered in my database
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$imail = $form->getValue('email');
$users = new Application_Model_DbTable_Users();
$row = $users->fetchRow($users->select('uid')->where('email = ".$imail."'));
/* if ($row == 1) {
$token = uniqid(mt_rand(), true);
$userpass = new Application_Model_DbTable_Password();
$userpass->addToken($uid , $token);
} else { $this->view->errorMessage = "Email not registered"; }
*/
//$this->emailAction();
}
i just need to get the id to be able to shift to my next function but i cant do it also
i think this might be unrelated but i did this on pure php and it works fine
if (isset($_POST['submit'])) {
$email = $_POST['email'];
$getemail = mysql_query("SELECT `uid` FROM `users` WHERE `email` ='$email'");
$resemail = mysql_num_rows($getemail);
if ($resemail == 0) {
echo "Email id is not registered";
}
$token = uniqid(mt_rand(), true);
$getoken = mysql_query("INSERT INTO `password_recovery` (`uid`,`token`) VALUES ((SELECT `uid` FROM `users` WHERE `email` = '$email'),'$token') ");
how can i do this logic in zendframework 1 thank you
Solution of Jehad Keriaki is correct, but unsafe. Use prepared statement syntax instead, for example:
$row = $users->fetchRow($users->select('uid')->where('email = ?', $imail));
It will protect you from SQL injection attack.
Try changing
$row = $users->fetchRow($users->select('uid')->where('email = ".$imail."'));
to
$row = $users->fetchRow($users->select('uid')->where('email = "$imail"'));
I think the issue is with the dots, which you still can use as:
$row = $users->fetchRow($users->select('uid')->where('email = "'.$imail.'"'));
I am learning PHP and MySQL and am having one or two problems with the build.
I have an HTML form that the user inputs their details and the details of a dog. The script then checks the database for the users name and the dogs name. If both exist within the database then the user_ID on the dog table is changed to change the ownership. If the User does not exist then the users details will be inputted into the database and the ownership changed.
I did have the whole thing working but was not using bindParam for the collection from the form and was advised this would be a much better option. This is where the fun started. I am now able to count the rows on the table using the script below, however, I am not able to use the WHERE clause within the SELECT query. I have tried placing "WHERE name_first = :name_first" but this failed with a "Parameter not defined" error.
I need to be able to user both the first and last name of the user to be able to select that users ID from the database.
I also have an other question in regards to the use of prepared statements. If I use the statement at the top of the script to SELECT from the database and all the forms inputs are bound to $STH, how do I then run a different query, for instance how do I INSERT the user details into the database using the same binds?
Could someone please have a look at the script and tell me where I am going wrong please?
<?php
/***mysql username***/
$user = 'root';
/***mysql password***/
$pass = '';
if ($_SERVER['REQUEST_METHOD'] == "POST") {
try {
$DBH = new PDO('mysql:host=localhost;dbname=kennel_cert;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//Queries
$sql1 = "SELECT user_ID FROM user_details";
$sql2 = "SELECT dog_ID FROM dog_details";
$STH = $DBH->prepare("SELECT * FROM user_details"); //Needs a WHERE clause to work
//var_export($STH);
//User details form
$STH->bindParam(':name_first', $_POST['name_first']);
$STH->bindParam(':name_last', $_POST['name_last']);
$STH->bindParam(':email', $_POST['email']);
$STH->bindParam(':telephone', $_POST['telephone']);
$STH->bindParam(':name_number', $_POST['name_number']);
$STH->bindParam(':street', $_POST['street']);
$STH->bindParam(':city', $_POST['city']);
$STH->bindParam(':county', $_POST['county']);
$STH->bindParam(':postcode', $_POST['postcode']);
//Dog details form
$STH->bindParam(':dog_reg', $_POST['dog_reg']);
$STH->bindParam(':name', $_POST['name']);
$STH->bindParam(':microchip', $_POST['microchip']);
$STH->bindParam(':gender', $_POST['gender']);
$STH->bindParam(':day', $_POST['day']);
$STH->bindParam(':month', $_POST['month']);
$STH->bindParam(':year', $_POST['year']);
$STH->execute(); //Execute the select script
//Use this to count the users - However without the WHERE it is counting all users not the one submitted into the form
if($STH->rowCount() > 0) {
echo "Exists <br>"; }
else {
echo "Doesn't exist <br>"; }
//var_export($userQuery); //Displays the contents of the query for testing
//Find if user exists in database - Again another way of counting the total but not the one inputed into the form
$userResult = $DBH->query($sql1);
if ($userResult !== false) {
$count = $userResult->rowCount();
echo 'Number of users: '.$count. '<br>';
foreach($userResult as $row) {
echo $row['user_ID'].'<br>';
}
}
//Find if dog exists in database - Again another way of counting the total but not the one inputed into the form
$dogResult = $DBH->query($sql2);
if ($dogResult !== false) {
$count = $dogResult->rowCount();
echo 'Number of dogs: '.$count. '<br>';
foreach($dogResult as $row) {
echo $row['dog_ID'].'<br>';
}
}
} catch (PDOException $e) {
echo $e->getMessage();
}
//echo "<p>Data submitted successfully</p>";
}
//Disconnect from the server
$DBH = null;
?>
OK so I have changed the query to look like this:
$sql = "SELECT user_ID
FROM user_details
WHERE name_first = :name_first
AND name_last = :name_last";
$STH = $DBH->prepare($sql);
When I run this I get this error:
PDOStatement::__set_state(array( 'queryString' => 'SELECT user_ID FROM user_details WHERE name_first = :name_first AND name_last = :name_last', ))
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
I am completely lost, I am going round in circle and can not find anything that is helping me to solve this.
I did have the script running as I stated using this setup, however, I was told to use the bindParam for the form and this is killing both the script and me.
<?php
/***mysql username***/
$user = 'root';
/***mysql password***/
$pass = '';
if ($_SERVER['REQUEST_METHOD'] == "POST") {
try {
$DBH = new PDO('mysql:host=localhost;dbname=kennel_cert;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//Queries
$userQuery = $DBH->query("SELECT user_ID FROM user_details WHERE name_first = '$first' AND name_last = '$last'"); //Checks if the user exists in the database
$dogQuery = $DBH->query("SELECT dog_ID FROM dog_details WHERE dog_ID = '$dog_reg' AND name = '$name' AND gender = '$gender'");
//User details form
$first = $_POST['name_first'];
$last = $_POST['name_last'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$name_number = $_POST['name_number'];
$street = $_POST['street'];
$city = $_POST['city'];
$county = $_POST['county'];
$postcode = $_POST['postcode'];
//Dog details form
$dog_reg = $_POST['dog_reg'];
$name = $_POST['name'];
$microchip = $_POST['microchip'];
$gender = $_POST['gender'];
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$u = ""; //Variable for counting users
$d = ""; //Variable for counting dogs
//var_export($userQuery); //Displays the contents of the query for testing
//Find if user exists in database
foreach($userQuery as $row1) { //Count the number of users in the database
$u++;
}
//Find if dog exists in database
foreach($dogQuery as $row2) { //Count the number of dogs in the database
$d++;
}
//The echos are for testing purposes
echo "Dog ID is: ".$row2['dog_ID']."<br>"; //Finds the ID of the dog and displays it
echo "User ID is: ".$row1['user_ID']."<br>"; //Finds the ID of the user and displays it
$newUserID = $row1['user_ID']; //Store the ID for future use
$newDogID = $row2['dog_ID']; //Store the ID for future use
//Perform if both user and dog exist
if ($u > 0 && $d > 0) { //If both the user and the dog exist in the database change the owner of the dog
echo "Both Match"; //Confirm both exist
$q = $DBH->prepare("UPDATE dog_details SET user_ID = '$newUserID' WHERE dog_ID = '$newDogID'"); //update the table to change ownership
$q->execute(); //Execute the change
}
// Perform if only dog exists
elseif ($u == 0 && $d > 0) { //If the user does not exist but the dog does.
echo "Dog matches but user does not exist"; //Confirm what exists
//Insert user details into user_details table and set the foreign user_ID key in the dog_details table
$q1 = $DBH->prepare("INSERT INTO user_details (name_first,name_last,email,telephone,name_number,street,city,county,postcode) VALUES ('$first','$last','$email','$telephone','$name_number','$street','$city','$county','$postcode')");
$q1->execute();
echo "<br>Insert complete<br>";*/
}
elseif ($u > 0 && $d == 0) {
echo "The dog does not exist - this is a problem";
//Form needs returning with values and asks user to check details
}
elseif ($u == 0 && $d == 0) {
echo "Both don't match";
}
} catch (PDOException $e) {
echo $e->getMessage();
}
//echo "<p>Data submitted successfully</p>";
}
//Disconnect from the server
$DBH = null;
?>
Check the manual you need to put the placeholders in the sql before binding parameters:
$query = "SELECT * FROM user_details
WHERE name_first = :name_first
AND name_last = :name_last
AND email = :email
etc...";
$STH = $DBH->prepare($query);