Using an if statement to update OR insert into - php

I have the following code which up dates my database table perfectly. However, I now wish it to either, update an existing row if the value of $status is 'open', or create a new row if the value of $status is 'completed'.
This is my code so far;
<?php
if (isset($_POST['submit_update_activity'])); {
require 'dbh.inc.php';
$activity_id = $_POST['hidden_activity_id'];
$idFromKnowledgeBase = $_POST['hidden_idFromKnowledgeBase'];
$hiddenUserID = $_POST['hidden_userId'];
$title = $_POST['title'];
$description = $_POST['description'];
$assigned_to = $_POST['assigned_to'];
$category = $_POST['category'];
$cost = $_POST['cost'];
$next_due = $_POST['next_due'];
$due_every = $_POST['due_every'];
$frequency = $_POST['frequency'];
$supplier = $_POST['supplier'];
$status = $_POST['status'];
$comments = $_POST['comments'];
$emptyAssignedTo = $_POST['empty_assigned_to'];
$emptyStatus = $_POST['empty_status'];
$emptyCategory = $_POST['empty_category'];
$dateCompleted = $_POST['date_completed'];
$emptyFrequency = $_POST['empty_frequency'];
$emptyNextDue = $_POST['empty_next_due'];
$next_due = date('Y-m-d', strtotime($dateCompleted. " + {$due_every} $frequency"));
if (empty($frequency)) {
$frequency = $emptyFrequency;
}
if (empty($status)) {
$status = $emptyStatus;
}
if (empty($assigned_to)) {
$assigned_to = $emptyAssignedTo;
}
if (empty($category)) {
$category = $emptyCategory;
}
//This line isn't working
if ($status == 'open') {
$next_due = $emptyNextDue;
} else {
$next_due = date('Y-m-d', strtotime($dateCompleted. " + {$due_every} $frequency"));
}
$stmt = $conn->prepare("UPDATE activities SET idFromKnowledgeBase = ?, userId = ?, title = ?, description = ?, assigned_to = ?, category = ?, cost = ?, last_completed = ?,next_due = ?, frequency = ?, supplier = ?, status = ?, comments = ? WHERE id = ?");
$stmt->bind_param("ssssssssssssss", $idFromKnowledgeBase, $hiddenUserID, $title, $description, $assigned_to, $category, $cost, $dateCompleted, $next_due, $frequency, $supplier, $status, $comments, $activity_id);
$stmt->execute();
if($stmt->affected_rows >0) {
header('Location: ../all_activities.php?updated');
}
}
?>
I've tried =, == and === for comparing $status. If I take it back a notch and echo either 'open' or 'completed' depending on the value of $status, it works fine, echoing the correct answer each time.
Advice is appreciated.

You are missing the INSERT statement
<?php
if (isset($_POST['submit_update_activity'])); {
require 'dbh.inc.php';
$activity_id = $_POST['hidden_activity_id'];
$idFromKnowledgeBase = $_POST['hidden_idFromKnowledgeBase'];
$hiddenUserID = $_POST['hidden_userId'];
$title = $_POST['title'];
$description = $_POST['description'];
$assigned_to = $_POST['assigned_to'];
$category = $_POST['category'];
$cost = $_POST['cost'];
$next_due = $_POST['next_due'];
$due_every = $_POST['due_every'];
$frequency = $_POST['frequency'];
$supplier = $_POST['supplier'];
$status = $_POST['status'];
$comments = $_POST['comments'];
$emptyAssignedTo = $_POST['empty_assigned_to'];
$emptyStatus = $_POST['empty_status'];
$emptyCategory = $_POST['empty_category'];
$dateCompleted = $_POST['date_completed'];
$emptyFrequency = $_POST['empty_frequency'];
$emptyNextDue = $_POST['empty_next_due'];
$next_due = date('Y-m-d', strtotime($dateCompleted. " + {$due_every} $frequency"));
if (empty($frequency)) {
$frequency = $emptyFrequency;
}
if (empty($status)) {
$status = $emptyStatus;
}
if (empty($assigned_to)) {
$assigned_to = $emptyAssignedTo;
}
if (empty($category)) {
$category = $emptyCategory;
}
//This line isn't working
if ($status == 'open') {
$next_due = $emptyNextDue;
} else {
$next_due = date('Y-m-d', strtotime($dateCompleted. " + {$due_every} $frequency"));
}
if($status == 'completed')
{
$stmt = $conn->prepare('INSERT INTO activities(idFromKnowledgeBase, userId, title , description, assigned_to, category, cost, last_completed,next_due, frequency, supplier , status, comments) VALUES(:kb, :uid, :title, :descr, :assign, :cat, :cost, :last, :next, :freq, :sup, :stat, :com)');
$stmt->execute(array(
'kb' => $idFromKnowledgeBase,
'uid' => $hiddenUserID,
'title' => $title,
'descr' => $description,
'assign' => $assigned_to,
'cat' => $category,
'cost' => $cost,
'last' => $dateCompleted,
'next' => $next_due,
'freq' => $frequency,
'sup' => $supplier,
'stat' => $status,
'com' => $comments,
));
}
else
{
$stmt = $conn->prepare("UPDATE activities SET idFromKnowledgeBase = :kb, userId = :uid, title = :title, description = :descr, assigned_to = :assign, category = :cat, cost = :cost, last_completed = :last,next_due = :next, frequency = :freq, supplier = :sup, status = :stat, comments = :com WHERE id = :id");
$stmt->execute(array(
'kb' => $idFromKnowledgeBase,
'uid' => $hiddenUserID,
'title' => $title,
'descr' => $description,
'assign' => $assigned_to,
'cat' => $category,
'cost' => $cost,
'last' => $dateCompleted,
'next' => $next_due,
'freq' => $frequency,
'sup' => $supplier,
'stat' => $status,
'com' => $comments,
'id' => $activity_id
));
}
if($stmt->affected_rows >0) {
header('Location: ../all_activities.php?updated');
}
}
?>

Related

UPDATE record serialized - php mysql

I have this problem, I have to update a record of a table that has the values of a serialized column. the call to the function works and passes the data correctly. I can enter the record, but I can not update. This is my code:
public function update($user_id, $array_check)
{
$arrayB = array();
$array_check = unserialize($array_check);
foreach ($array_check $key => $value) {
if($value["id"] == $array_check){
$idRow = $value["id"];
if($value["value"] == "0"){
$valueRow = "1";
}else{
$valueRow = "0";
}
}else{
$idRow = $value["id"];
$valueRow = $value["value"];
}
$row = array("id" => $idRow, "value" => $valueRow);
$arrayB[] = $row;
}
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = :docs_selected WHERE user_id = :user_id');
$row = $stmt->execute(array(':user_id' => $user_id, ':docs_selected' => serialize($arrayB) ) );
return $arrayB;
}
edit.
Replace this:
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = :docs_selected WHERE user_id = :user_id);
with:
$deseralized = serialize($arrayB);
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = '$deseralized ' WHERE user_id = '$user_id');

How can I rewrite my function to only accept array? Help me to find error

I'm trying to make my notification function receive an array, but when I try to send my data, it fails with this error message:
Error Number: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''4168' AND type = 'low stock'' at line 1 SELECT COUNT(*) AS notificationCount FROM storelte_notifications WHERE product_id IN '4168' AND type = 'low stock' Filename: models/Notification.php
My new function (rewritten to accept array):
public function addNotification($data){
$types = array('new' => 0, 'pending' => 1, 'low stock' => 2);
if (isset($types[$data['type']]) === false) {
throw new \InvalidArgumentException('Value for third parameter must be one of new, pending, or low stock.');
}
$type = $types[$data['type']];
$timestamp = time();
$query = "SELECT COUNT(*) AS notificationCount FROM storelte_notifications WHERE product_id IN ? AND type = ? ";
$previousNotification = $this->db->query($query, array($data['product_id'],$data['type']))->result_array();
if ($previousNotification[0]['notificationCount'] == 0) {
$sql = "INSERT INTO storelte_notifications (message,type,product_id,user_id,timestamp) VALUES(?, ?, ?, ?, ?)";
try {
foreach ($data['product_id'] as $pid) {
if (!$this->db->query($sql, array($data['message'], $data['type'], $pid, $data['user_id'], $timestamp))) {
return false;
}
}
return true;
} catch (Exception $e) {
}
}else{
return true;
}
}
My old function (with use of separated parameters):
public function addNotification($message, $product_id, $user_id, $type = ''){
$types = array('new' => 0, 'pending' => 1, 'low stock' => 2);
if (isset($types[$type]) === false) {
throw new \InvalidArgumentException('Value for third parameter must be one of new, pending, or low stock.');
}
$type = $types[$type];
$timestamp = time();
$query = "SELECT COUNT(*) AS notificationCount FROM storelte_notifications WHERE product_id IN ? AND type = ? ";
$previousNotification = $this->db->query($query, array($product_id, $type))->result_array();
if ($previousNotification[0]['notificationCount'] == 0) {
$sql = "INSERT INTO storelte_notifications (message,type,product_id,user_id,timestamp) VALUES(?, ?, ?, ?, ?)";
try {
foreach ($product_id as $pid) {
if (!$this->db->query($sql, array($message, $type, $pid, $user_id, $timestamp))) {
return false;
}
}
return true;
} catch (Exception $e) {
}
}else{
return true;
}
}
this tests let me to add more than once
public function addNotification(Array $data) {
/*$types = array('new' => 0, 'pending' => 1, 'low stock' => 2);
if (isset($types[$data['type']]) === false) {
throw new \InvalidArgumentException('Value for third parameter must be one of new, pending, or low stock.');
}
$type = $types[$data['type']];
$query = "SELECT COUNT(*) AS notificationCount FROM storelte_notifications WHERE product_id = ? AND type = ? ";
$previousNotification = $this->db->query($query, array($data['product_id'],$data['type']))->result_array();
if ($previousNotification[0]['notificationCount'] == 0) {
$sql = "INSERT INTO storelte_notifications (message,type,product_id,user_id,timestamp) VALUES(?, ?, ?, ?, ?)";
try {*/
//foreach ($data as $pid) {
//if( !$this->db->query($sql, array($data['message'], $data['type'], $data['product_id'], $data['user_id'], $data['timestamp'])) ) {
$sql = "INSERT INTO storelte_notifications (message,type,product_id,user_id,timestamp) VALUES(?, ?, ?, ?, ?)";
$this->db->query($sql, array($data['message'], $data['type'], $data['product_id'], $data['user_id'], $data['timestamp']));
//return false;
// }
//}
//return true;
//} catch (Exception $e) {
//}
//} else {
// return true;
//}
}
So, my new function $data parameter looks like this:
$entryData = array(
'message' => 'low stock',
'product_id' => $value['id'],
'user_id' => $this->session->log['id'],
'type' => 'low stock'
);
And I'm calling it like this:
$this->notification->addNotification($entryData);
Can anybody tell me where is the error?
Thanks!
right syntax to use near ''4168'
Looks like your user_id SQL WHERE part is generated with additional apostrophe, but it is not expected to be there.
Code looks fine, can you try this code queue?
Firstly, replace your new function with this:
public function addNotification(Array $data) {
$types = array('new' => 0, 'pending' => 1, 'low stock' => 2);
if (isset($types[$data['type']]) === false) {
throw new \InvalidArgumentException('Value for third parameter must be one of new, pending, or low stock.');
}
$type = $types[$data['type']];
$timestamp = time();
$query = "SELECT COUNT(*) AS notificationCount FROM storelte_notifications WHERE product_id IN ? AND type = ? ";
$previousNotification = $this->db->query($query, array($data['product_id'],$data['type']))->result_array();
if ($previousNotification[0]['notificationCount'] == 0) {
$sql = "INSERT INTO storelte_notifications (message,type,product_id,user_id,timestamp) VALUES(?, ?, ?, ?, ?)";
try {
foreach ($data['product_id'] as $pid) {
if( !$this->db->query($sql, array($data['message'], $data['type'], $pid, $data['user_id'], $timestamp)) ) {
return false;
}
}
return true;
} catch (Exception $e) {
}
} else {
return true;
}
}
Then, try executing this:
$entryData = array(
'message' => 'low stock',
'product_id' => array($value['id']),
'user_id' => $this->session->log['id'],
'type' => 'low stock'
);
$this->notification->addNotification($entryData);
And see if it will work.
This is written in codeigniter right? Make use of Active Record
public function addNotification($data)
{
$types = array(
'new' => 0,
'pending' => 1,
'low stock' => 2
);
if (isset($types[$data['type']]) === false) {
throw new \InvalidArgumentException('Value for third parameter must be one of new, pending, or low stock.');
}
$type = $types[$data['type']];
$timestamp = time();
$select = array(
"COUNT(*) AS notificationCount"
);
$where = array(
"type" => $data['type'])
);
$this->db->select($select);
$this->db->where($where);
$this->db->where_in('product_id', $data['product_id']);
$query = $this->db->get('storelte_notifications');
$previousNotification = $query->row();
if ($previousNotification->notificationCount > 0)
{
return true;
}
else
{
if ($data['product_id']) {
foreach ($data['product_id'] as $pid) {
$insert_fields = array(
"message" => $data['message'],
"type" => $data['type'],
"product_id"=> $pid,
"user_id" => $data['user_id'],
"timestamp" => time()
);
$this->db->insert('storelte_notifications', $insert_fields);
}
return true;
}
return false;
}
}
use bracket in your in clause
SELECT COUNT(*) AS notificationCount FROM storelte_notifications WHERE product_id IN (?) AND type = ? ";

Uploading a file with date

I have a page that upload files to my database, im trying to record the day when the file is uploaded so i can check and view it to my table, but everytime i upload a file, it doesnt record any dates
<?php
function upload_image()
{
if ( isset($_FILES["user_image"]) )
{
$date = date('M-D-Y');
$destination = './upload/' . $_FILES['user_image']['name'];
move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
return $_FILES['user_image']['name'];
}
}
function get_image_name($user_id)
{
include('db3.php');
$statement = $connection->prepare("SELECT image FROM users1 WHERE id = '$user_id'");
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
return $row["image"];
}
}
function get_total_all_records()
{
include('db3.php');
$statement = $connection->prepare("SELECT * FROM users1");
$statement->execute();
$result = $statement->fetchAll();
return $statement->rowCount();
}
?>
My Insert Query:
<?php
include('db3.php');
include('function.php');
if(isset($_POST["operation"]))
{
if($_POST["operation"] == "Add")
{
$image = '';
if($_FILES["user_image"]["name"] != '')
{
$image = upload_image();
}
$statement = $connection->prepare("
INSERT INTO users1 (memorandum, titlee, image, date)
VALUES (:memorandum, :titlee, :image, date)
");
$result = $statement->execute(
array(
':memorandum' => $_POST["memorandum"],
':date' => $_POST["date"],
':titlee' => $_POST["titlee"],
':image' => $image
)
);
if(!empty($result))
{
echo 'Data Inserted';
}
}
if($_POST["operation"] == "Edit")
{
$image = '';
if($_FILES["user_image"]["name"] != '')
{
$image = upload_image();
}
else
{
$image = $_POST["hidden_user_image"];
}
$statement = $connection->prepare(
"UPDATE users1
SET memorandum = :memorandum, titlee = :titlee, image = :image , date = :date ,
WHERE id = :id
"
);
$result = $statement->execute(
array(
':memorandum' => $_POST["memorandum"],
':titlee' => $_POST["titlee"],
':date' => $_POST["date"],
':image' => $image,
':id' => $_POST["user_id"]
)
);
if(!empty($result))
{
echo 'Data Updated';
}
}
}
?>

Joomfish migration script returns error

Here is a script that upgrades joomfish (joomla translation component) from joomla 1.5 to 2.5:
$db = new PDO("mysql:host=localhost;dbname=db;charset=UTF8", "root", "pass");
$stmt = $db->prepare("select distinct(jfc.reference_id),c.catid,jfc.language_id,c.modified,c.modified_by,c.version,c.modified_by ,c.ordering,c.created_by,c.metadesc ,c.created_by_alias from jos_jf_content jfc ,jos_content c where jfc.reference_id = c.id and jfc.reference_table = 'content' ");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
$count_row = $db->prepare("select * from jos_jf_content where reference_id = ? and language_id = ?");
$count_row->bindValue(1, $row['reference_id']);
$count_row->bindValue(2, $row['language_id']);
$lang_code = $db->prepare("select lang_code from j25_languages where lang_id = ?");
$lang_code->bindValue(1, $row['language_id']);
$lang_code->execute();
$l_code = $lang_code->fetch(PDO::FETCH_OBJ);
$language_code = $l_code->lang_code;
$count_row->execute();
$title ="";
$fulltext ="";
$introtext ="";
$alias ="";
$published ="";
while($col = $count_row->fetch(PDO :: FETCH_ASSOC))
{
if($col['reference_field'] == "title")
{
$title = $col['value'];
}
if($col['reference_field'] == "fulltext")
{
$fulltext = $col['value'];
}
if($col['reference_field'] == "introtext")
{
$introtext = $col['value'];
}
if($col['reference_field'] == "alias")
{
$alias = $col['value'];
}
$published = $col['published'];
}
$exe = $db->prepare("insert into j25_content (`title`,`alias`,`introtext`,`fulltext`,`published`,`catid`,`created`,`created_by`,`created_by_alias`,`modified`,`modified_by`,`version`,`ordering`,`metadesc`,`language`) values(:title,:alias,:introtext,:fulltext,:published,:categoryid,:created,:created_by,:created_by_alias,:modified,:modified_by,:version,:ordering,:metadesc,:language_code)");
$exe->execute(array(':title' => $title,':alias' => $alias,':introtext' => addslashes($introtext),':fulltext' => addslashes($fulltext),':published' => ".$published.",':categoryid' => $row['catid'],':created' => date("Y-m-d H:i:s"),':created_by' => $row['created_by'],':created_by_alias' => "".$row['created_by_alias']."",':modified' => date("Y-m-d H:i:s"),':modified_by' =>$row['modified_by'],':version' => $row['version'],':ordering' => $row['ordering'],':metadesc' => $row['metadesc'],':language_code' => $language_code));
$i = $db->lastInsertId('id');
$asst = $db->prepare("select asset_id from j25_categories where id = ? ");
$asst->bindValue(1, $row['catid']);
$asst->execute();
$asst_id = $asst->fetch(PDO::FETCH_OBJ);
$cassetid = $asst_id->asset_id;
$sel = $db->prepare("select lft,rgt FROM `j25_assets` where id = (SELECT max(id) FROM `j25_assets`)");
$sel->execute();
$select = $sel->fetch(PDO::FETCH_OBJ);
$left = $select->lft;
$right = $select->rgt;
$left=$left+1;
$right = $right+1;
$stmt = $db->prepare("insert into j25_assets (`parent_id`,`lft`,`rgt`,`level`,`name`,`title`) values(:cassetid,:left,:right,:level,:name,:title)");
$stmt->execute(array(':cassetid' => $cassetid,':left' => $left,':right' => $right,':level' => 4,':name' => "com_content.article.".$i,':title' => $title));
$insertedId = $db->lastInsertId('id');
$update = $db->prepare("update j25_content set asset_id = ? where id = ?");
$update->bindValue(1, $insertedId);
$update->bindValue(2, $i);
$update->execute();
$stmt = $db->prepare("insert into j25_jf_translationmap (language,reference_id,translation_id,reference_table) values (:language_code,:reference_id,:translation_id,:content)");
$stmt->execute(array(':language_code' => $language_code,':reference_id' => $row['reference_id'],':translation_id' => $i,':content' => 'content'));
}
Line of code:
$language_code = $l_code->lang_code;
Returns:
Trying to get property of non-object
I'm not an author of the script and not good in PHP, but I've tried to print_r($l_code->lang_code); and I got expected result en-GB from [lang_code] => en-GB. What I need to change in this code? Thanks.
The line $language_code = $l_code->lang_code > 0; sets $language_code to boolean value. Try var_dump($l_code); and var_dump($language_code); to debug your results. You should also check if $l_code actually is an object, or perhaps null was returned. Hope that helps.

Get the newest data from sql but not working

I would like to get the newest comments in following code, but now only showing the oldest 50 comments, how can I edit code to showing the newest 50 comments? thanks so much
Code here:
<?php
class comments extends db_connect
{
private $requestFrom = 0;
private $language = 'en';
public function __construct($dbo = NULL)
{
parent::__construct($dbo);
}
public function allCommentsCount()
{
$stmt = $this->db->prepare("SELECT max(id) FROM comments");
$stmt->execute();
return $number_of_rows = $stmt->fetchColumn();
}
public function count($postId)
{
$stmt = $this->db->prepare("SELECT count(*) FROM comments WHERE postId = (:postId) AND removeAt = 0");
$stmt->bindParam(":postId", $postId, PDO::PARAM_INT);
$stmt->execute();
return $number_of_rows = $stmt->fetchColumn();
}
public function create($postId, $text, $notifyId = 0)
{
$result = array("error" => true,
"error_code" => ERROR_UNKNOWN);
if (strlen($text) == 0) {
return $result;
}
$post = new post($this->db);
$postInfo = $post->info($postId);
unset($post);
$currentTime = time();
$ip_addr = helper::ip_addr();
$u_agent = helper::u_agent();
$stmt = $this->db->prepare("INSERT INTO comments (fromUserId, postId, comment, createAt, notifyId, ip_addr, u_agent) value (:fromUserId, :postId, :comment, :createAt, :notifyId, :ip_addr, :u_agent)");
$stmt->bindParam(":fromUserId", $this->requestFrom, PDO::PARAM_INT);
$stmt->bindParam(":postId", $postId, PDO::PARAM_INT);
$stmt->bindParam(":comment", $text, PDO::PARAM_STR);
$stmt->bindParam(":createAt", $currentTime, PDO::PARAM_INT);
$stmt->bindParam(":notifyId", $notifyId, PDO::PARAM_INT);
$stmt->bindParam(":ip_addr", $ip_addr, PDO::PARAM_STR);
$stmt->bindParam(":u_agent", $u_agent, PDO::PARAM_STR);
if ($stmt->execute()) {
$result = array("error" => false,
"error_code" => ERROR_SUCCESS,
"commentId" => $this->db->lastInsertId(),
"comment" => $this->info($this->db->lastInsertId()));
if ($this->requestFrom != $postInfo['fromUserId']) {
$gcm = new gcm($this->db, $postInfo['fromUserId']);
$gcm->setData(GCM_NOTIFY_COMMENT, "You have a new comment.", $postId);
$gcm->send();
}
}
return $result;
}
public function remove($commentId)
{
$result = array("error" => true,
"error_code" => ERROR_UNKNOWN);
$commentInfo = $this->info($commentId);
if ($commentInfo['error'] === true) {
return $result;
}
// if ($commentInfo['fromUserId'] != $this->requestFrom) {
//
// return $result;
// }
$currentTime = time();
$stmt = $this->db->prepare("UPDATE comments SET removeAt = (:removeAt) WHERE id = (:commentId)");
$stmt->bindParam(":commentId", $commentId, PDO::PARAM_INT);
$stmt->bindParam(":removeAt", $currentTime, PDO::PARAM_INT);
if ($stmt->execute()) {
$result = array("error" => false,
"error_code" => ERROR_SUCCESS);
}
return $result;
}
public function removeAll($postId) {
$currentTime = time();
$stmt = $this->db->prepare("UPDATE comments SET removeAt = (:removeAt) WHERE postId = (:postId)");
$stmt->bindParam(":postId", $postId, PDO::PARAM_INT);
$stmt->bindParam(":removeAt", $currentTime, PDO::PARAM_INT);
}
public function info($commentId)
{
$result = array("error" => true,
"error_code" => ERROR_UNKNOWN);
$stmt = $this->db->prepare("SELECT * FROM comments WHERE id = (:commentId) LIMIT 1");
$stmt->bindParam(":commentId", $commentId, PDO::PARAM_INT);
if ($stmt->execute()) {
if ($stmt->rowCount() > 0) {
$row = $stmt->fetch();
$time = new language($this->db, $this->language);
$profile = new profile($this->db, $row['fromUserId']);
$fromUserId = $profile->get();
unset($profile);
$lowPhotoUrl = "/img/profile_default_photo.png";
if (strlen($fromUserId['lowPhotoUrl']) != 0) {
$lowPhotoUrl = $fromUserId['lowPhotoUrl'];
}
$post = new post($this->db);
$post->setRequestFrom($this->getRequestFrom());
$postInfo = $post->info($row['postId']);
$result = array("error" => false,
"error_code" => ERROR_SUCCESS,
"id" => $row['id'],
"fromUserId" => $row['fromUserId'],
"fromUserState" => $fromUserId['state'],
"fromUserUsername" => $fromUserId['username'],
"fromUserFullname" => $fromUserId['fullname'],
"fromUserPhotoUrl" => $lowPhotoUrl,
"postId" => $row['postId'],
"postFromUserId" => $postInfo['fromUserId'],
"comment" => htmlspecialchars_decode(stripslashes($row['comment'])),
"createAt" => $row['createAt'],
"notifyId" => $row['notifyId'],
"timeAgo" => $time->timeAgo($row['createAt']));
}
}
return $result;
}
public function get($postId, $commentId = 0)
{
if ($commentId == 0) {
$commentId = $this->allCommentsCount() + 1;
}
$comments = array("error" => false,
"error_code" => ERROR_SUCCESS,
"commentId" => $commentId,
"postId" => $postId,
"comments" => array());
$stmt = $this->db->prepare("SELECT id FROM comments WHERE postId = (:postId) AND id < (:commentId) AND removeAt = 0 ORDER BY id ASC LIMIT 0,38");
$stmt->bindParam(':postId', $postId, PDO::PARAM_INT);
$stmt->bindParam(':commentId', $commentId, PDO::PARAM_INT);
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
$commentInfo = $this->info($row['id']);
array_push($comments['comments'], $commentInfo);
$comments['commentId'] = $commentInfo['id'];
unset($commentInfo);
}
}
return $comments;
}
public function getPreview($postId)
{
$commentId = $this->allCommentsCount() + 1;
$comments = array("error" => false,
"error_code" => ERROR_SUCCESS,
"commentId" => $commentId,
"postId" => $postId,
"count" => $this->count($postId),
"comments" => array());
$stmt = $this->db->prepare("SELECT id FROM comments WHERE postId = (:postId) AND id < (:commentId) AND removeAt = 0 ORDER BY id ASC LIMIT 3");
$stmt->bindParam(':postId', $postId, PDO::PARAM_INT);
$stmt->bindParam(':commentId', $commentId, PDO::PARAM_INT);
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
$commentInfo = $this->info($row['id']);
array_push($comments['comments'], $commentInfo);
$comments['commentId'] = $commentInfo['id'];
unset($commentInfo);
}
}
return $comments;
}
public function setLanguage($language)
{
$this->language = $language;
}
public function getLanguage()
{
return $this->language;
}
public function setRequestFrom($requestFrom)
{
$this->requestFrom = $requestFrom;
}
public function getRequestFrom()
{
return $this->requestFrom;
}
}
Try to edit your LIMIT from LIMIT 0,38 to LIMIT 38.

Categories