Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am having trouble with a function for a PHP/MySQL instant messaging system. A variable ($sql) is defined as a MySQL query, which is then queried, and returns a resource ID. However, the following while statement returns 'Array' instead of its supposed contents.
<?php
// Fetches a summary of the conversations.
function fetch_conversation_summary(){
$sql = "SELECT
`conversations`.`conversation_id`,
`conversations`.`conversation_subject`,
MAX(`conversations_messages`.`message_date`) AS `conversation_last_reply`,
MAX(`conversations_messages`.`message_date`) > `conversations_members`.`conversation_last_view` AS `conversation_unread`
FROM `conversations`
LEFT JOIN `conversations_messages` ON `conversations`.`conversation_id` = `conversations_messages`.`conversation_id`
INNER JOIN `conversations_members` ON `conversations`.`conversation_id` = `conversations_messages`.`conversation_id`
WHERE `conversations_members`.`user_id` = {$_SESSION['user_id']}
AND `conversations_members`.`conversation_deleted` = 0
GROUP BY `conversations`.`conversation_id`
ORDER BY `conversation_last_reply` DESC";
$result = mysql_query($sql);
$conversations = array();
while (($row = mysql_fetch_assoc($result)) !== false){
$conversations[] = array(
'id' => $row['conversation_id'],
'subject' => $row['conversation_subject'],
'last_reply' => $row['conversation_last_reply'],
'unread_messages' => ($row['conversation_unread'] == 1),
);
}
return $conversations;
}
// Fetches all of the messages in the given converstion.
function fetch_conversation_messages($conversation_id){
$conversation_id = (int)$conversation_id;
$sql = "SELECT
`conversations_messages`.`message_date`,
`conversations_messages`.`message_date` > `conversations_members`.`conversation_last_view` AS `message_unread`,
`conversations_messages`.`message_text`,
`users`.`user_name`
FROM `conversations_messages`
INNER JOIN `users` ON `conversations_messages`.`user_id` = `users`.`user_id`
INNER JOIN `conversations_members` ON `conversations_messages`.`conversation_id` = `conversations_members`.`conversation_id`
WHERE `conversations_messages`.`conversation_id` = {$conversation_id}
AND `conversations_members`.`user_id` = {$_SESSION['user_id']}
ORDER BY `conversations_messages`.`message_date` DESC";
$result = mysql_query($sql);
echo $result;
$messages = array();
while (($row = mysql_fetch_assoc($result)) !== false){
$messages[] = array(
'date' => $row['message_date'],
'unread' => $row['message_unread'],
'text' => $row['message_text'],
'user_name' => $row['user_name'],
);
}
var_dump( $messages );
}
// Sets the last view time to the current time for the given conversation.
function update_conversation_last_view($conversation_id){
$conversation_id = (int)$conversation_id;
$time = time() + 18000;
$sql ="UPDATE `conversations_members`
SET `conversation_last_view` = {$time}
WHERE `conversation_id` = {$conversation_id}
AND `user_id` = {$_SESSION['user_id']}";
mysql_query($sql);
}
// Creates a new conversation, making the given users a member.
function create_conversation($user_ids, $subject, $body){
$subject = mysql_real_escape_string(htmlentities($subject));
$body = mysql_real_escape_string(htmlentities($body));
mysql_query("INSERT INTO `conversations` (`conversation_subject`) VALUES ('{$subject}')");
$conversation_id = mysql_insert_id();
$sql = "INSERT INTO `conversations_messages` (`conversation_id`, `user_id`, `message_date`, `message_text`)
VALUES ({$conversation_id}, {$_SESSION['user_id']}, UNIX_TIMESTAMP(), '{$body}')";
mysql_query($sql);
$values = array("({$conversation_id}, {$_SESSION['user_id']}, UNIX_TIMESTAMP(), 0)");
foreach ($user_ids as $user_id){
$user_id = (int)$user_id;
$values = array("({$conversation_id}, {$_SESSION['user_id']}, UNIX_TIMESTAMP(), 0)"); }
$sql = "INSERT INTO `conversations_members` (`conversation_id`, `user_id`, `conversation_last_view`, `conversation_deleted`)
VALUES " . implode(", ", $values);
mysql_query($sql);
}
// Checks to see if the given user is a member of the given conversation.
function validate_conversation_id($conversation_id){
$conversation_id = (int)$conversation_id;
$sql = "SELECT COUNT(1)
FROM `conversations_members`
WHERE `conversation_id` = {$conversation_id}
AND `user_id` = {$_SESSION['user_id']}
AND `conversation_deleted` = 0";
$result = mysql_query($sql);
return(mysql_result($result, 0) == 1);
}
// Adds a message to the given conversation.
function add_conversation_message($conversation_id, $text){
$conversation_id = (int)$conversation_id;
$text = mysql_real_escape_string(htmlentities($text));
$sql = "INSERT INTO `conversations_messages` (`conversation_id`, `user_id`, `message_date`, `message_text`)
VALUES ({$conversation_id}, {$_SESSION['user_id']}, UNIX_TIMESTAMP(), '{$text}')";
mysql_query($sql);
mysql_query("UPDATE `conversations_members` SET `conversation_deleted` = 0 where `conversation_id = {$conversation_id}");
}
// Deletes (or marks as deleted) a given conversation.
function delete_conversation($conversation_id){
$conversation_id = (int)$conversation_id;
$sql = "SELECT DISTINCT `conversation_deleted`
FROM `conversations_members`
WHERE `user_id` != {$_SESSION['user_id']}
AND `conversation_id` = {$conversation_id}";
$result = mysql_query($sql);
//if (mysql_num_rows($result) == 1 && mysql_result($result, 0) == 1){
if (mysql_num_rows($result) == 0){
mysql_query("DELETE FROM `conversations` WHERE `conversation_id` = {$conversation_id}");
mysql_query("DELETE FROM `conversations_members` WHERE `conversation_id` = {$conversation_id}");
mysql_query("DELETE FROM `conversations_messages` WHERE `conversation_id` = {$conversation_id}");
}else{
$sql = "UPDATE `conversations_members`
SET `conversation_deleted` = 1
WHERE `conversation_id` = {$conversation_id}
AND `user_id` = {$_SESSION['user_id']}";
mysql_query($sql);
}
}
?>
I have tried echoing the error, $messages (as you can see from the code). In addition, I have echoed the result of the SQL query.
Update: I did the mentioned var_dump and my result was:
Resource id #16array(0) { } Array ( )
Sure it prints Array because that is what $messages is. If you want to print the contents of $messages you can use var_dump or print_r.
Similar reason for $result. $result is a resource type (at least as long as the query is successful). Printing it does not make sense since it is an internal reference. You have to pass it to a function like mysql_fetch_assoc or mysql_fetch_array or similar that can process such a resource.
Regarding your updated question: This output tells you that your array is empty and does not contain any elements. Are you sure your SQL-Query returns any rows?
Related
I am trying to get the key value from the multidimensinal array which I have created using .The Array snapshot is given after the Code.
Below is my PHP code-
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link,$selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if($numOfTicket > 0){
$allRowData = array();
while($row = mysqli_fetch_assoc($rsTicket)){
$allRowData[] = $row;
}
$key = 'array(1)[ticketID]';
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', array_keys($key)).")";
Array Snapshot-
I need the tickedID value from this array . Like the first one is 49 .
Please help.
change your code like
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link, $selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if ($numOfTicket > 0) {
$allRowData = array();
while ($row = mysqli_fetch_assoc($rsTicket)) {
$allRowData[] = $row['ticketID'];
}
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (" . implode(',', $allRowData) . ")";
$ids = array_column( $allRowData, 'ticketID'); //this will take all ids as new array
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', $ids).")";
You should do a single query using JOIN for this:
$query = "
SELECT t.*
FROM ticket t
JOIN ticketusermapping tum
ON t.ticketID = tum.ticketID
AND tum.userID = '$userID'
AND tum.distanceofticket <= '$miles'
";
$stmt = mysqli_query($link, $query);
$numOfTickets = mysqli_num_rows($stmt);
while($row = mysqli_fetch_assoc($stmt)){
var_dump($row); // here will be the ticket data
}
I'm trying almost everything to add a new key and its value to a result query.
$consulta = "SELECT p.id_empleado,count(p.id_empleado) as pendientes,e.nombre,e.apellidos FROM partidas_empleados p ";
$consulta.= "inner join empleados e on p.id_empleado=e.id_empleado ";
$consulta.= "WHERE abierta=TRUE group by id_empleado";
$sql = $con->prepare($consulta);
$ok = $sql->execute();
$query = $sql->fetchAll(PDO::FETCH_ASSOC);
for($i=0;$i<count($query);$i++){
//echo "hola";
$fila = $query[$i];
$consulta = "SELECT id_partida FROM partidas_empleados where id_empleado=? ";
$sql = $con->prepare($consulta);
$ok = $sql->execute(array($fila['id_empleado']));
$sub_query = $sql->fetchAll(PDO::FETCH_ASSOC);
//echo $sub_query;
//$fila[]= array("lista_partidas"=>$sub_query);
$fila['lista_partidas']= $sub_query;
}
$sub_query is just a list of asociative arrays
I'm trying to add $sub_query to $query with lista_partidas as a key.
As #kunruh and #jeroen said I was creating a copy of and modifying that copy.
$consulta = "SELECT p.id_empleado,count(p.id_empleado) as pendientes,e.nombre,e.apellidos FROM partidas_empleados p ";
$consulta.= "inner join empleados e on p.id_empleado=e.id_empleado ";
$consulta.= "WHERE abierta=TRUE group by id_empleado";
$sql = $con->prepare($consulta);
$ok = $sql->execute();
$query = $sql->fetchAll(PDO::FETCH_ASSOC);
for($i=0;$i<count($query);$i++){
$consulta = "SELECT id_partida FROM partidas_empleados where id_empleado=? ";
$sql = $con->prepare($consulta);
$ok = $sql->execute(array($fila['id_empleado']));
$sub_query = $sql->fetchAll(PDO::FETCH_ASSOC);
$query[$i]['lista_partidas']= $sub_query;
}
This is my code and I don't know why IF/ELSE statement is not working
$user_id = $_POST['user_id'];
$strSQL = "SELECT chat.user_id,max(date) max_date ,user.user_id,user.firstname,user.lastname,user.picture
FROM ( select from_user_id as user_id,date,isread from chat
WHERE to_user_id = '$user_id'
Union select to_user_id as user_id,date,isread from chat WHERE from_user_id = '$user_id' ) as chat join user on user.user_id = chat.user_id
where user.status != 'block' group by chat.user_id order by max_date DESC";
$chatdata = array();
$objQuery = mysql_query($strSQL);
while($row = mysql_fetch_assoc($objQuery)){
$frduser_id = $row['user_id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$picture = $row['picture'];
$strSQL2 = "SELECT isread from chat WHERE to_user_id = '$user_id' and from_user_id = '$frduser_id'
ORDER BY date DESC LIMIT 1";
//array_push($chatdata, $row);
$objQuery2 = mysql_query($strSQL2);
if (empty($objQuery2)) {
$row2 = 1;
$result = array_merge($row, $row2);
array_push($chatdata,$result);
}else{
$row2 = mysql_fetch_assoc($objQuery2);
$result = array_merge($row, $row2);
array_push($chatdata,$result);
}
}
You can use mysql_num_rows to get count of rows inside results.
$objQuery2 = mysql_query($strSQL2);
$objQuery2Rows = mysql_num_rows($strSQL2);
if ( $objQuery2Rows < 1) {
$row2 = 1;
$result = array_merge($row, $row2);
array_push($chatdata,$result);
}else{
$row2 = mysql_fetch_assoc($objQuery2);
$result = array_merge($row, $row2);
array_push($chatdata,$result);
}
I'm making a form that submits a story into a MySQL table called 'work'. I want to later take the id of the newly created record and put the information into a different table.
But when I submit the story, it says:
$workid is undefined.
I can't see the problem though because I believe I've defined it?
<?php
if (!empty($_POST) && !empty($_POST['title']) && !empty($_POST['story']) && !empty($_POST['genre']) && !empty($_POST['rating'])) {
$title = strip_tags($_POST['title']);
$story = strip_tags($_POST['story']);
$title = mysqli_real_escape_string($db, $title);
$story = mysqli_real_escape_string($db, $story);
$genre = $_POST['genre'];
$rating = $_POST['rating'];
$query = "SELECT COUNT(*) AS count FROM works WHERE Title = '".$title."'";
$result = $db->query($query);
$data = $result->fetch_assoc();
if ($data['count'] > 0) {
echo "<p>Story already exists!</p>";
} else {
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$query = "SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc())
$workid = $row["id"]; //workid is written here but still considered undefined
}
$query = "INSERT INTO `author_work` (`author_id`) VALUES ('".$authorid."')";
$result = $db->query($query);
$query = "INSERT INTO `author_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`login_id`) VALUES ('".$userid."')";
$result = $db->query($query);
if ($result) {
echo "<p>Story submitted!</p>";
} else {
echo "SQL Error: " . $db->error;
}
}
}
?>
You never did a $db->query() on your INSERT INTO... query string, so it was never inserted, and was overwritten by your SELECT id ... query.
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$db->query($query); // Missing this $db->query()
$query="SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row= $result->fetch_assoc())
$workid = $row["id"];}
Your $workid might not be initialized, depending on your condition and the result of your SQL query: so try to avoid next operations that will causes warnings/errors by using continue or else
Good day,
As mention in the topic, I'm creating a ajax function where the php will directly update the status then if the status is 1 (or approve), it will compare between 2 table (tblcompany and tblinternapplication) and doing insert new company if the company not in the list. I tried test one by one it function well but after combine it doesn't add any new company when the person application approved (or set to 1) even the status in tblinternapplication updated. Below is my code.
<?php require_once("../includes/session.php"); ?>
<?php require_once("sessioncourse.php"); ?>
<?php confirm_logged_in(); ?>
<?php require_once("../includes/connection.php") ?>
<?php require_once("../includes/functions.php") ?>
<?php
$id = $_GET['id'];
$status =$_GET['status'];
$sql="UPDATE tblinternapplication set status_approval =
".mysql_real_escape_string($status) ." WHERE id = " .mysql_real_escape_string($id);
$result = mysql_query($sql);
$querysel = "SELECT i.company_code, c.company_name as cn, i.company_name as ic,
c.company_branch as cb, i.company_branch as ib, FROM tblcompany c,
tblinternapplication i WHERE i.id = '$id' ";
$resultsel = mysql_query($querysel, $connection);
$queryselc = "SELECT
company_name, company_branch,
company_address, post_code,
company_city, company_state,
company_country,
company_phone, company_fax,
company_url FROM tblinternapplication WHERE id = '$id' ";
$resultselc = mysql_query($queryselc, $connection);
if ($status == 1){
while($rowsel = mysql_fetch_array($resultsel)){
if($rowsel['company_code'] == NULL){
if(($rowsel['cn'] != $rowsel['ic']) OR ($rowsel['ib'] != $rowsel['cb'])){
while($rowselc = mysql_fetch_array($resultselc)){
$query = "INSERT INTO tblcompany (
company_name, company_branch,
company_address, post_code,
company_city, company_state, company_country,
company_phone, company_fax,
company_url
) VALUES (
'{$rowselc['company_name']}', '{$rowselc['company_branch']}',
'{$rowselc['company_address']}','{$rowselc['post_code']}',
'{$rowselc['company_city']}','{$rowselc['company_state']}',
'{$rowselc['company_country']}',
'{$rowselc['company_phone']}','{$rowselc['company_fax']}',
'{$rowselc['company_url']}'
)";
$resultc = mysql_query($query, $connection);
}
}
}
}
}
?>
Just to share the answer using my own method. Basically I remove 2-level nested while and make the first query row match then the second is to search for result. Hope this will help others.
<?php
$id = $_GET['id'];
$status = $_GET['status'];
$sql="UPDATE tblinternapplication set status_approval =
".mysql_real_escape_string($status) ." WHERE id = " .mysql_real_escape_string($id);
$result = mysql_query($sql);
$querysel = "SELECT i.company_code, i.company_name, i.company_branch, c.company_name,
c.company_branch FROM tblinternapplication i, tblcompany c WHERE i.company_name =
c.company_name AND i.company_branch = c.company_branch AND i.id = '$id' ";
$resultsel = mysql_query($querysel, $connection);
$queryselc = "SELECT * FROM tblinternapplication where id = '$id'";
$resultselc = mysql_query($queryselc, $connection);
if ($status == 1){
if(mysql_num_rows($resultsel) == 0){
while($rowselc = mysql_fetch_array($resultselc)){
$query = "INSERT INTO tblcompany (
company_name, company_branch,
company_address, post_code,
company_city, company_state, company_country,
company_phone, company_fax,
company_url
) VALUES (
'{$rowselc['company_name']}', '{$rowselc['company_branch']}',
'{$rowselc['company_address']}','{$rowselc['post_code']}',
'{$rowselc['company_city']}','{$rowselc['company_state']}',
'{$rowselc['company_country']}',
'{$rowselc['company_phone']}','{$rowselc['company_fax']}',
'{$rowselc['company_url']}'
)";
$resultc = mysql_query($query, $connection);
}
}
}
?>
if anyone have recommendation welcome to leave comments.
Thank you.