foreach loop with PHP and PDO - php

this mysql update:
function updateOrder($id_array){
$count = 1;
foreach ($id_array as $id){
$update = mysqli_query($this->connect,"UPDATE `table_name` SET `order_id` = $count WHERE id = $id");
$count ++;
}
return true;
}
i'll change to PDO , this my write code but can work .
but that is not reflected in the db
function update($id_array,$_table){
$query = "UPDATE `table_name` SET `order_id` = ? WHERE id = ?";
$stmt = $this->conn->prepare($query);
$count = 1;
foreach ($id_array as $id) {
$stmt->execute(array(':$count' => $count, ':id' => $id));
$count ++;
}
return true;
}
call funtion :
$idArray = explode(",",$_POST['ids']);<br>
$db->update($idArray);

use:
$stmt->execute(array(':count' => $count, ':id' => $id));
instead of
$stmt->execute(array(':$count' => $count, ':id' => $id));
:$count to :count

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

Queries in loop taking too much time to execute

I am trying to update data with Ajax and PHP. The following script updating data, But its taking too much time to run.
PHP
$groupId = $_POST['group_id'];
$Id_array = $_POST['Id'];
$result_array = $_POST['result'];
$data = array();
if(count($_POST['data']) > 0 && !empty ($_POST['data'])){
foreach($_POST['data'] as $key => $array){
$row = array();
$row['team_id'] = intval($array['team_id']);
$row['Note'] = strip_tags(trim(strval($array['Note'])));
$data[$key] = $row;
}
for ($i = 0; $i < count($Id_array); $i++) {
$Id = intval($Id_array[$i]);
$result = strip_tags(trim(strval($result_array[$i])));
$sql1 = $db->prepare("UPDATE teams SET result = :result WHERE id = :id ");
foreach($data as $key => $array){
$sql1 ->execute(array(':result' => $result, ':id' => $Id));
}
$sql2 = $db->prepare("UPDATE teams SET note = :note WHERE team_id = :teamid AND group_id = :group_id");
foreach($data as $key => $array){
$sql2->execute(array(':note' => $array['Note'], ':teamid' => $array['team_id'], ':group_id' => $groupId ));
}
Network Timing
You don't need this loop:
foreach($data as $key => $array){
$sql1 ->execute(array(':result' => $result, ':id' => $Id));
}
It's updating the same ID repeatedly, since $Id doesn't change in the loop. Just do:
$sql1->execute(array(':result' => $result, ':id' => $Id));
once.
You can also get some small improvements by doing:
$sql1 = $db->prepare("UPDATE teams SET result = :result WHERE id = :id ");
$sql2 = $db->prepare("UPDATE teams SET note = :note WHERE team_id = :teamid AND group_id = :group_id");
just once, before any of the loops.
Another problem is that you have this loop:
foreach($data as $key => $array){
$sql2->execute(array(':note' => $array['Note'], ':teamid' => $array['team_id'], ':group_id' => $groupId ));
}
inside the for() loop, but it doesn't use any of the variables that change each time through the loop. So it's re-executing all the same queries for each ID in $Id_array.
Take it out of the loop.
With all these changes, the code now looks like:
$groupId = $_POST['group_id'];
$Id_array = $_POST['Id'];
$result_array = $_POST['result'];
$sql1 = $db->prepare("UPDATE teams SET result = :result WHERE id = :id ");
$sql2 = $db->prepare("UPDATE teams SET note = :note WHERE team_id = :teamid AND group_id = :group_id");
$data = array();
if(count($_POST['data']) > 0 && !empty ($_POST['data'])){
foreach($_POST['data'] as $key => $array){
$row = array();
$row['team_id'] = intval($array['team_id']);
$row['Note'] = strip_tags(trim(strval($array['Note'])));
$data[$key] = $row;
}
foreach ($Id_array as $i => $Id) {
$Id = intval($Id);
$result = strip_tags(trim(strval($result_array[$i])));
$sql1 ->execute(array(':result' => $result, ':id' => $Id));
}
foreach($data as $key => $array){
$sql2->execute(array(':note' => $array['Note'], ':teamid' => $array['team_id'], ':group_id' => $groupId ));
}
}
I would use a transaction instead of auto committing in a loop.
So,
//PDO::beginTransaction ( void )
$dbh->beginTransaction();
foreach () {
$smt->exec();
}
//PDO::commit ( void )
$dbh->commit();
Also, you only need to prepare a statement one time since you're binding your variables in the execute function, so try keeping any prepare statements out of a loop.
This should help with some of the overhead of the query in the loop.

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.

PHP else statement not executing

My else statement is not getting executed when it should. There are no errors in the code. It simply has to do with the flow of my query and foreach statement but I cannot seem to figure this out. Any ideas?
$id = $this->input->post('id');
$session_id = $this->input->post('session_id');
$q1 = $this->db->query("SELECT *
FROM default_cart
WHERE cookie_id = '$session_id'
AND product_id = '$id' LIMIT 1");
foreach($q1->result() as $row) {
if($row->cookie_id != $session_id && $row->product_id != $id) {
echo json_encode(array('error_code' => 'e100'));
} else {
$data = array('product_id' => $id,
'active' => 'Yes',
'cookie_id' => $session_id
);
$this->db->insert('default_cart', $data);
echo json_encode(array('success' => true));
}
}
First, I would like to suggest that there is no sense of looping through the query when there is only one record LIMIT 1 and no sense of if check while you have already checked the all parameters in the query WHERE cookie_id = '$session_id' AND product_id = '$id' just fetch the row returned by the query and check for empty or not.
$id = $this->input->post('id');
$session_id = $this->input->post('session_id');
$q1 = $this->db->query("SELECT * FROM default_cart
WHERE cookie_id = '$session_id' AND product_id = '$id' LIMIT 1");
$row=$q1->row();
if(!empty($row)) {
$data = array('product_id' => $id,
'active' => 'Yes',
'cookie_id' => $session_id);
$this->db->insert('default_cart', $data);
echo json_encode(array('success' => true));
}else{
echo json_encode(array('error_code' => 'e100'));
}

Categories