Avoid recurring of Records in the code - php

I am implementing Wordpress feature, viewing posts per Year and Month using PHP as
eg:
Press Releases
2013(4)
October(1)
Announcement1
But I am getting each records as repeated in the result. The code is as shown below:
$query = "SELECT * FROM edu_announcements WHERE status = '1' ORDER BY add_time asc";
$resultSet = mysql_query($query);
if (mysql_num_rows($resultSet))
{
$newsArray = array();
echo '<ul>' . PHP_EOL;
echo '<li><strong>Press releases:</strong></li>' . PHP_EOL;
while ($newsResult = mysql_fetch_array($resultSet))
{
$newDate = $newsResult['add_time'] ;
$timePeriod =date("F Y", $newDate);
//$timePeriod = date('F Y ',strtotime($newDate));
$timePeriodY = date('Y',$newDate);
$timePeriodM = date('F',$newDate);
if (!isset($newsArray[$timePeriod]))
{
$newsArray[$timePeriod] = array();
}
$newsArray[$timePeriod][] = $newsResult;
}
foreach ($newsArray as $timePeriod => $newsItems)
{
$timePeriodY = date('Y',strtotime($timePeriod));
echo '<li><strong>' . $timePeriodY . '</strong>' . PHP_EOL;
echo '<ul>' . PHP_EOL;
//by month
foreach ($newsArray as $timePeriod => $newsItems)
{
echo '<li><strong>' . $timePeriod . '</strong>' . PHP_EOL;
echo '<ul>' . PHP_EOL;
//news items
foreach ($newsItems as $item)
{
echo '<li>';
echo ''.$item["title"].'';
echo '</li>' . PHP_EOL;
}
//end by month
echo '</ul>' . PHP_EOL;
echo '</li>' . PHP_EOL;
}
//end by year
echo '</ul>' . PHP_EOL;
echo '</li>' . PHP_EOL;
}
echo '<li> </li>' . PHP_EOL;
echo '</ul>' . PHP_EOL;
}
else {
echo 'No announcements';
}
I am getting the result as repeated as shown below:
Array ( [July 2013] => Array ( [0] => Array ( [0] => 99 [id] => 99 [1] => sdfsdf [title] => sdfsdf [2] =>
sdfsdfsdfc
[description] =>
sdfsdfsdfc
[3] => [documents] => [4] => [photo1] => [5] => [photo2] => [6] => [photo3] => [7] => [photo4] => [8] => 1 [public_visibility] => 1 [9] => 0 [dept_visibility] => 0 [10] => 0 [depatment] => 0 [11] => 1373913000 [add_time] => 1373913000 [12] => 1 [status] => 1 [13] => sdfsdf [small_description] => sdfsdf ) [1] => Array ( [0] => 100 [id] => 100 [1] => sefsdfvsxdf [title] => sefsdfvsxdf [2] =>
sdfsdfsd
[description] =>
sdfsdfsd
[3] => [documents] => [4] => [photo1] => [5] => [photo2] => [6] => [photo3] => [7] => [photo4] => [8] => 1 [public_visibility] => 1 [9] => 0 [dept_visibility] => 0 [10] => 0 [depatment] => 0 [11] => 1374604200 [add_time] => 1374604200 [12] => 1 [status] => 1 [13] => sdfsefs [small_description] => sdfsefs ) )
I want distinct records from the table. Can anyone help me to solve this.

If you mean why are you getting the parts of each record duplicated, such as:
[0] => 99
[id] => 99
it is because mysql_fetch_array has a second option (beyond your $resultset), which defaults to int $result_type = MYSQL_BOTH.
The type of array that is to be fetched. It's a constant and can
take the following values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH.
If you must use the raw (and old) mysql functions (as others say, this is no longer good practice), then you will also want to probably add , MYSQL_ASSOC to the function call, and then deal only with the name of the columns - such as 'id', 'title' & 'description'. There may also be similar parameters to other DB access calls, though mostly they will use the MYSQL_ASSOC-style returns to have the column name by default.

I solved the answer by using the code as shown below:
echo '<div id="news_events_section_wrapper">
<div class="news_events_section">';
$CURRENT_TIMESTAMP=time();
$sqlstr=mysql_query("select * from nesote_edu_announcements where status=1");
$count=mysql_num_rows($sqlstr);
if($count!=0)
{
while($article=mysql_fetch_row($sqlstr))
{
$id=$article[0];
$details= $article[2];
$postedon=date("F j, Y",$article[11]);
$olderpost=date("Y",$article[11]);
$yearnoquery=mysql_query("select count(*) from nesote_edu_announcements where add_time <='$CURRENT_TIMESTAMP' and status=1 ");
$resultq=mysql_fetch_row($yearnoquery);
$numberofposts=$resultq[0];
}
echo "<a href=javascript:showmonths(".$id.") style=".'"'."text-decoration:none".'"><div>';
echo $olderpost;echo '(';echo $numberofposts;echo ')';
echo '</div>
</a>';
$monthqry=mysql_query("SELECT add_time,COUNT(id),id FROM nesote_edu_announcements WHERE status=1 AND (add_time <='$CURRENT_TIMESTAMP') AND FROM_UNIXTIME(add_time, '%Y')='$olderpost' GROUP BY FROM_UNIXTIME(add_time, '%M') ASC");
while($month=mysql_fetch_row($monthqry))
{
$monthsfordisplay=date("F",$month[0]);
$months=date("m",$month[0]);
$monthnos=$month[1];
$artid=$month[2];
echo '<div id='.'"'."month_art".'"'." class=".'"'."month_"; echo $id.'">';
echo '<a href="javascript:showdetails'.'('; echo $artid; echo ')">'; echo $monthsfordisplay;
echo '('; echo $monthnos; echo ')</a></div>';
$smalldisquery=mysql_query("SELECT * FROM nesote_edu_announcements WHERE FROM_UNIXTIME(add_time, '%m')='$months' AND add_time <='$CURRENT_TIMESTAMP' and status=1");
while($smalldisc=mysql_fetch_row($smalldisquery))
{
$articlemonthid=$smalldisc[0];
$disc=$smalldisc[1];
echo ' <div style="display:none;" id="sub_str" class="smalldiscription_';echo $artid; echo '">
<a href='.'"index.php?page=events/announcementdetails/'; echo $articlemonthid; echo '"'.' style='.'"text-decoration:none;'.'">
<font color="#80000">';
$message=substr($disc,0,30);
$message=$message."...";
echo "* ".$message; echo "</font></a>";
echo "</div>";
}
}
}
echo "</div></div>";
This will show announcements in Year-Month basis.

Related

Failed MySQL insert with no error, binding values in execute, PHP

I am trying to insert data from an array into MySQL in PHP. I have been working on this for a long time and could use some help debugging. I am not getting any errors which is making it hard for me to find the problem. Any help I could get with this would be appreciated.
There are more than two items in the $productConfigArray, I only included a sample.
Here is the code:
function insertBatch($productConfigArray)
{
try {
$insertStatement = 'INSERT INTO productconfigTEST (productid, partid, currency, fobid, fobpostalcode, pricetype) VALUES';
foreach ($productConfigArray as $index => $row) {
$productId = $row['0'];
$partId = $row['1'];
$currency = $row['2'];
$fobId = $row['3'];
$fobPostalCode = $row['4'];
$priceType = $row['5'];
$insertStatement .= ' (:productId' . $index .', :partId' . $index .', :currency' . $index .', :fobId' . $index .', :fobPostalCode' . $index .', :priceType' . $index .')';
$insertParams['productId' . $index] = $productId;
$insertParams['partId' . $index] = $partId;
$insertParams['currency' . $index] = $currency;
$insertParams['fobId' . $index] = $fobId;
$insertParams['fobPostalCode' . $index] = $fobPostalCode;
$insertParams['priceType' . $index] = $priceType;
}
$productConfigStatement = $pdo->prepare($insertStatement);
$productConfigStatement->execute($insertParams);
} catch(Exeption $e) {
echo $e->getMessage();
}
}
The $productConfigArray is structured like this:
Array
(
[0] => Array
(
[0] => 0011-02
[1] => 0011-02BK
[2] => USD
[3] => 15068
[4] => 15068
[5] => Net
)
[1] => Array
(
[0] => 0011-05
[1] => 0011-05BK
[2] => USD
[3] => 15068
[4] => 15068
[5] => Net
)
)
The completed $insertStatement (after foreach):
"INSERT INTO productconfigTEST (productid, partid, currency, fobid, fobpostalcode, pricetype, configtype) VALUES (:productId0, :partId0, :currency0, :fobId0, :fobPostalCode0, :priceType0) (:productId1, :partId1, :currency1, :fobId1, :fobPostalCode1, :priceType1)"
The completed $insertParams:
Array ( [productId0] => 0011-02 [partId0] => 0011-02BK [currency0] => USD [fobId0] => 15068 [fobPostalCode0] => 15068 [priceType0] => Net [productId1] => 0011-05 [partId1] => 0011-05BK [currency1] => USD [fobId1] => 15068 [fobPostalCode1] => 15068 [priceType1] => Net )

need help in mutidimensional array

Good evening my helpers!
I have a multidimensional array $data like this:
Array
(
[0] => thunderteszt
[1] => orevikod
[2] => 5400
[3] => 6
)
Array
(
[0] => bakterhaz1982
[1] => $s$w$0ffТΉЏИÐΞЯ
[2] => 5540
[3] => 3
)
Array
(
[0] => bakterhaz1982
[1] => $s$w$0ffТΉЏИÐΞЯ
[2] => 5570
[3] => 2
)
Array
(
[0] => bakterhaz1982
[1] => $s$w$0ffТΉЏИÐΞЯ
[2] => 5740
[3] => 1
)
Array
(
[0] => thunderteszt
[1] => orevikod
[2] => 5840
[3] => 5
)
Array
(
[0] => thunderteszt
[1] => orevikod
[2] => 5890
[3] => 4
)
You can see I have arrays with repeated nick in row[1] ($s$w$0ffТΉЏИÐΞЯ).
I will pick up the lowest value (row[2]) from the repeated arrays.
Therafter I will make a new array from the picked values and I will see only the following:
Array
(
[0] => thunderteszt
[1] => orevikod
[2] => 5400
[3] => 6
)
Array
(
[0] => bakterhaz1982
[1] => $s$w$0ffТΉЏИÐΞЯ
[2] => 5540
[3] => 3
)
edit:
I forgot to say: the array already mutisorted by score(row 2) then by nick (row 1)
edit2:
my code sample is the following:
edit3:
Sorry for caps lock in original question :(
function pts_panel_on($aseco) {
global $pts;
$maniapos = -1;
$linkmaniapos = -0.2;
$linkmaniapos2 = -0;
$xml = '<manialinks><manialink id="40400">';
$xml .= '<frame posn="48.2 15 0">';
if (empty($pts->finish)) return true;
$beerok=array();
foreach($pts->finish as $key=>$row){
$becenev[$key] = $row['nick'];
$ido[$key] = $row['score'];
}
array_multisort($ido, SORT_ASC, $becenev, SORT_ASC, $pts->finish );
foreach($pts->finish as $data){
print_r(array_values($data));
$rpointinc++;
$linkmaniapos = ($linkmaniapos - 3) ;
$linkmaniapos2 = ($linkmaniapos2 - 3) ;
$maniapos = ($maniapos - 3) ;
if ($rpointinc <= 10) {
$xml .= '<format textsize="1"/><label posn="-19.3 ' . $linkmaniapos. '
1.5" sizen="30 3 2" scale="0.3" style="TextRaceChrono" halign="center"
text="$s$0f0'.$rpointinc .' "/>';
$xml .= '<format textsize="1"/><label posn="-27.5 ' . $linkmaniapos . ' 1.5"
sizen="30 3 2" halign="left" scale="0.3" style="TextRaceChrono"
text="$s$fff'.formatTime($data['score']).' "/>';
$xml .= '<format textsize="1.7"/><label posn="-16.5 ' . $linkmaniapos . '
1.6" sizen="12 3 2" halign="left" text="$000' . $data['nick'] . ' "/>';
$xml .= '<quad sizen="4 3" posn="-19.6 ' . $maniapos . ' 1" valign="center"
halign="center" style="Bgs1InRace" substyle="NavButton" />';
$xml .= '<quad sizen="6.2 3" posn="-24.9 ' . $maniapos . ' 1"
valign="center" halign="center" style="Bgs1InRace" substyle="NavButton" />';
$xml .= '<quad sizen="17 3" posn="-17.4 ' . $maniapos . ' 1.1"
valign="center" halign="left" style="Bgs1InRace" substyle="NavButton"/>';
}
}
$xml .= '</frame>';
$xml .= '</manialink></manialinks>';
foreach ($pts->Players as $data2) {
$aseco->client->query("SendDisplayManialinkPageToLogin", $data2['login'],
$xml, 0, false);
}
}

PHP : traversing multidimensional array

I've an array in library management system that has a user on first index,books assigned to that user on next index and then details about books assigned like this.
this is what i need to show in table form
Array
(
[user] => Array
(
[0] => stdClass Object
(
[id] => 5
[name] =>
[email] => test#test.com
[password] => test
[role] =>
[status] => 1
)
)
[books] => Array
(
[0] => stdClass Object
(
[id] => 1
[user_id] => 5
[book_id] => 1
[date_issue] => 2016-07-24 00:00:00
[date_return] => 2016-07-25 00:00:00
)
[1] => stdClass Object
(
[id] => 2
[user_id] => 5
[book_id] => 2
[date_issue] => 2016-07-24 00:00:00
[date_return] => 2016-07-25 00:00:00
)
[2] => stdClass Object
(
[id] => 3
[user_id] => 5
[book_id] => 1
[date_issue] => 2016-07-25 00:00:00
[date_return] => 2016-07-25 00:00:00
)
)
[bookdata] => Array
(
[0] => Array
(
[0] => stdClass Object
(
[id] => 1
[title] => PHP Made Easy
[author] => Dietel & Dietel
[serial_no] => 232323
[qty] => 9
[row_no] => 1
[col_no] => 2
[status] => 1
[category_id] => 1
[description] => This is a book about php
)
)
[1] => Array
(
[0] => stdClass Object
(
[id] => 2
[title] => C++
[author] => Dietel & Dietel
[serial_no] => 232323
[qty] => 9
[row_no] => 1
[col_no] => 2
[status] => 1
[category_id] => 1
[description] => This is a book about c++
)
)
[2] => Array
(
[0] => stdClass Object
(
[id] => 1
[title] => PHP Made Easy
[author] => Dietel & Dietel
[serial_no] => 232323
[qty] => 9
[row_no] => 1
[col_no] => 2
[status] => 1
[category_id] => 1
[description] => This is a book about php
)
)
)
)
this is how i try to parse like this
foreach ($data as $key=> $value) {
echo $key[$value]->id;
}
the error i get
Severity: Warning
Message: Illegal offset type
Filename: views/history.php
Line Number: 4
Please help me to parse this array
this array object, try to get object as array by using like this.
$data_new = (array) $data;
This will convert your array object to array format.after that you can pass this to foreach.
or else you can use below function
function object_to_array($obj) {
$arr = is_object($obj) ? get_object_vars($obj) : $obj;
foreach ($arr as $key => $val) {
$val = (is_array($val) || is_object($val)) ? object_to_array($val) : $val;
$arr[$key] = $val;
}
return $arr;
}
This is not an actual direct answer for your question,But i am suggesting you that you can try in this way too,If answer is helped mark as answer :).
I would suggest you this,
Stop looping this type of multidimensional array. This array formation is wrong if you are expecting output shown in post.
Try to remove extra unnecessary nesting
[0] => Array (
[0] => stdClass Object
(
[id] => 1
[title] => PHP Made Easy
Divide you array and save it in different variable for e.g.
$userInfo = $array[user][0];
$books = $array[books];
$bookdata = $array[bookdata];
Here onwards you can loop and start adding data to your empty array maintaining key/per record. This key will help you to loop it in a table...
According to your array structure, it's a an array object.
You have to use call array key name to traverse array objects within your main loop. So you can do it as below mention.
//main loop
foreach ($data as $key=> $value) {
//get user info
echo $value['user'][0]->id;
//get books info
for($i=0; $i < count($value['books']); $i++) {
echo $value['books'][$i]->id;
}
//get further books info
foreach($value['bookdata'] as $books) {
echo $books->author;
}
}
Now you can use this to populate HTML table.
Since you have only a single user per array, you could just loop through the array; using conditional Logic to decide the Current Key (like books, user)... and from there, you can just build a HTML Table containing your required Output. A test might be in Order and you can find the test here.
<?php
$tblOutput = "<div class='books-wrapper col-md-12'>" . PHP_EOL;
if(!empty($arrBkLib)){
foreach($arrBkLib as $key=>$data){
if($key == 'user' && !empty($data[0])){
$userName = isset($data[0]->name) ? $data[0]->name : "N/A";
$tblOutput .= "<div class='user-data-pane col-md-6 pull-left'>" . PHP_EOL;
$tblOutput .= "<span class='btn btn-custom'>{$userName}</span>" . PHP_EOL;
$tblOutput .= "</div>" . PHP_EOL;
$tblOutput .= "<div class='action-pane col-md-6 pull-right'>" . PHP_EOL;
$tblOutput .= "<a class='btn btn-custom'>Ban User</a>" . PHP_EOL;
$tblOutput .= "</div>" . PHP_EOL;
$tblOutput .= "<table class='tbl-books-data'>" . PHP_EOL;
$tblOutput .= "<tr class='tbl-books-data-head-row'>" . PHP_EOL;
$tblOutput .= "<th class='tbl-books-data-head-cell'>Book</th>" . PHP_EOL;
$tblOutput .= "<th class='tbl-books-data-head-cell'>Issue Date</th>" . PHP_EOL;
$tblOutput .= "<th class='tbl-books-data-head-cell'>Return Date</th>" . PHP_EOL;
$tblOutput .= "<th class='tbl-books-data-head-cell'>Fine</th>" . PHP_EOL;
$tblOutput .= "<th class='tbl-books-data-head-cell'>Status</th>" . PHP_EOL;
$tblOutput .= "</tr>" . PHP_EOL;
}else if($key == 'books' && !empty($data)){
foreach($data as $iKey=>$books) {
$issueDate = isset($books->date_issue) ? date("d/m/Y", strtotime($books->date_issue)) : "N/A";
$returnDate = isset($books->date_return) ? date("d/m/Y", strtotime($books->date_return)) : "N/A";
$bookName = isset($arrBkLib['bookdata'][$iKey]->title) ? $arrBkLib['bookdata'][$iKey]->title : "N/A";
$status = isset($arrBkLib['bookdata'][$iKey]->status) ? $arrBkLib['bookdata'][$iKey]->status : "N/A";
$fine = "N/A"; // USE YOUR LOGIC HERE TO DETERMINE THIS VALUE...
$tblOutput .= "<tr class='tbl-books-data-row'>" . PHP_EOL;
$tblOutput .= "<th class='tbl-books-data-cell'>{$bookName}</th>" . PHP_EOL;
$tblOutput .= "<th class='tbl-books-data-cell'>{$issueDate}</th>" . PHP_EOL;
$tblOutput .= "<th class='tbl-books-data-cell'>{$returnDate}</th>" . PHP_EOL;
$tblOutput .= "<th class='tbl-books-data-cell'>{$fine}</th>" . PHP_EOL;
$tblOutput .= "<th class='tbl-books-data-cell'>{$status}</th>" . PHP_EOL;
$tblOutput .= "</tr>" . PHP_EOL;
}
}
}
$tblOutput .= "</table>" . PHP_EOL;
$tblOutput .= "</div>" . PHP_EOL;
}
echo $tblOutput;

PHP foreach multi array

I use the https://github.com/humanmade/Custom-Meta-Boxes/ to make this custom repeatable custom fields to wordpress. The given arrays are like this
Array
(
[0] => Array
(
[photoset-caption] => Array
(
[cmb-field-0] => Caption1
[cmb-field-1] => Caption2
[cmb-field-2] => Caption3
[cmb-field-3] => Caption4
)
[photoset-image] => Array
(
[cmb-field-0] => 17
[cmb-field-1] => 16
[cmb-field-2] => 15
[cmb-field-3] => 14
)
)
[1] => Array
(
[photoset-caption] => Array
(
[cmb-field-0] => Caption1
[cmb-field-1] => Caption2
[cmb-field-2] => Caption3
[cmb-field-3] => Caption4
)
[photoset-image] => Array
(
[cmb-field-0] => 17
[cmb-field-1] => 16
[cmb-field-2] => 15
[cmb-field-3] => 14
)
)
)
The loop it try to make is this.
// get the custom fields for this post
$photoset = get_post_meta($post->ID, 'photoset_group_fields', false );
echo '<div class="photoset">';
echo '<div class="photoset-row">';
foreach($photoset as $photosetloop){
echo '<figure class="photoset-item">';
echo '<div>' . wp_get_attachment_image($photosetloop['photoset-image'], 'large' ) . '</div>';
echo '<figcaption>' . $photosetloop['photoset-caption'] .'</figcaption>';
echo '</figure>';
}
echo '</div>';
echo '</div>';
So the loop haves .photoset-item and inside it have image and caption.
My question how to I foreach it, thanks.
I did update for the array, i have group that I loop.
The simplest way it's to make two foreachs, you can do it recursive with a function if you want as well.
<?php
$photos =array(
'photoset-caption' => array(
'cmb-field-0' => 'Caption1',
'cmb-field-1' => 'Caption2',
'cmb-field-2' => 'Caption3',
'cmb-field-3' => 'Caption4'
),
'photoset-image' => array(
'cmb-field-0' => 17,
'cmb-field-1' => 16,
'cmb-field-2' => 15,
'cmb-field-3' => 14
)
);
foreach($photos as $k => $photo){
echo '<h1>'.$k.'</h1>';
foreach($photo as $key => $value){
echo $key.': '. $value.'<br/>';
}
echo '<hr/>';
}
Check an example here: example
Not the most elegant way to do it, but it does work in this case.
$arr = Array
(
"photoset-caption" => Array
(
"cmb-field-0" => "Caption1",
"cmb-field-1" => "Caption2",
"cmb-field-2" => "Caption3",
"cmb-field-3" => "Caption4"
),
"photoset-image" => Array
(
"cmb-field-0" => 17,
"cmb-field-1" => 16,
"cmb-field-2" => 15,
"cmb-field-3" => 14
)
);
$count = count($arr["photoset-caption"]);
for($i = 0; $i < $count; ++$i) {
echo 'Loop #'.$i.'<br>';
echo $arr["photoset-caption"]["cmb-field-".$i], '<br>';
echo $arr["photoset-image"]["cmb-field-".$i], '<br>';
echo '<br>';
}
You can paste it here:
http://writecodeonline.com/php/

Grouping by date in php/mysql

I have a an array:
Array
(
[0] => Array
(
[id] => 53
[product] => something
[price] => £78
[quantity] => 23
[time] => 2011-07-15 20:29:21
)
[1] => Array
(
[id] => 52
[product] => product
[price] => £89
[quantity] => 1
[time] => 2011-07-14 00:51:57
)
[2] => Array
(
[id] => 51
[product] => product
[price] => £89
[quantity] => 1
[time] => 2011-07-14 00:51:37
))
I got this using the following sql statement:
select * from some_table GROUP BY time DESC
I want to display the results ordered by date, with the date as a heading:
e.g.
**2011-07-15**
all array elements for above date go here
**2011-07-15**
all array elements for above date go here
I thought about doing a seperate statement for each seperate day, but that sounds wrong. Is there a better way?
ORDER BY Time in your query, like this:
select * from some_table ORDER BY time DESC
Then loop in PHP:
$last_date = 0;
while($row = mysql_fetch_assoc($result)){
$date = date('Y-m-d', strtotime($row['time']));
if($date != $last_date)
echo '**'.$date.'**';
$last_date = $date;
echo '<br />';
echo 'Id: '.$row['Id'];
echo 'Product: '.$row['product'];
echo 'Price: '.$row['price'];
echo 'Quantity: '.$row['quantity'];
echo '<br /><br />';
}
If you're ouputting to a console instead of an HTML page then replace the '<br \>' with "\n"
<?
$arrDate = Array
(
[0] => Array
(
[id] => 53
[product] => something
[price] => £78
[quantity] => 23
[time] => 2011-07-15 20:29:21
);
$currentDate = null;
foreach ($arrDate as $item) {
if ($item["time"] == $currentDate) {
// print details
}
else {
$currentDate = $arrDate["time"];
// print date header.
// print details
}
}
?>

Categories