I'm work on PHP CMS , almost done of it
I use the Material Design Lite pop-up share menu, this required a html id property
as ex. if I post 2 articles and share menu has same id number then, when user press on a one of them the 2 will appear
so I need PHP code that do this for me, I don't need a very difficult script
just need a script do this :
1 - make a variable contains id = 0
2 - add 1
3 - store the new value , id = 1
4 - repeat for every post
I tried this code :
<?php
$id = 0;
echo $id += 1 ;
$id = $id ;
?>
thanks in advance
If you want global counter you can save it to filesystem:
<?php
$idstr = file_get_contents("counter.txt");
$id = intval($idstr)+1;
file_put_contents("counter.txt", $id);
echo($id);
?>
Related
Is there any way to create a new a href that remembers all the submitted data earlier. I don't know how to say it properly so I will describe in the code:
The first button
Click me
After the user clicks it, he is redirected to the same page but with the new button :
Click me
And so on :
Click me
How do i create the n variable to be added and increased after the button is pressed ?
( I have a table displayed from a database by using the while command with mysqli_fetch_array($database); )
The table is created like (trivial ) :
$retrieve_items = mysql_query("SELECT * FROM items WHERE id > 0");
$col = 0;
echo '<table width=100% border= 1><tr>';
while($row = mysql_fetch_array( $retrieve_items )) {
$col ++;
echo '<td>'.$row['name_item'].'</td>';
if ($col % 5 == 0 )
{
echo '</tr><tr>';
}
}
echo '</tr></table>';
I recommend not to try managing numbered variable names. If there is no important reason to do so, it will make your logic unnecessarily complicated.
PHP understands array parameters in e.g. $_GET. They are passed from HTML with empty braces appended to the parameter name.
This is a little demo to illustrate this alternative approach:
<?php
// get the passed array or generate a new one
$n = isset($_GET['n']) ? (array) $_GET['n'] : [];
//ppend 2 random numbers
$n[] = rand(1,100);
$n[] = rand(1,100);
//output the link with GET parameters in query
?>
the link
<!-- or let PHP's built-in generate a propper query --><br>
the link
Be aware, that the second link generated by http_build_query contains indexes of the array, which are commonly based on 0.
in php, to access the current query String, you can use
$_SERVER['QUERY_STRING']
so you could so something like
Click me
or you could replace your previous value in the query string
[edited] I need to display posts from database sorted in a kinda specific way.
There is a page which at set time interval query database via ajax to pull 180 latest post. Each post in db has column "source" which can be "instagram" or "twitter". Ajax returns 30 sets (or less) x 6 posts each (less if there is not enough posts). Than with help of js all sets are hidden and only one set (6 posts) is displayed at a time. After few seconds set is hidden and next one is shown. Think of it like a typical slideshow but with posts instead of images on infinite loop.
At the begining it wasn't important what kind of post were in sets. It could be all 6 posts from twitter or instagram or mixed. But as usual when project was scheduled to finish, I was asked to change the way sets are generated. Now client wants to have only 2 types of sets with posts in particular order (described below).
So my question is how change this (simplified example from my ajax file):
DB details for ref.: table POSTS: id / source / user / date etc.
$sql="SELECT * FROM posts ORDER BY id DESC LIMIT 180";
...
$stmt->setFetchMode(PDO::FETCH_OBJ);
$set=1;
while($row = $stmt->fetch()) {
if($set==1){
echo '<!--start set--><div class="set">';
}
if($row->source="twitter"){
echo '<div class="post twitter">';
echo '{all stuff related to this twitter post}';
echo '</div>';
} else if($row->source="instagram") {
echo '<div class="post instagram">';
echo '{all stuff related to this instagram post}';
echo '</div>';
}
if($set==6) {
echo '</div> <!--//END set-->';
$set=0;
}
}
$set++
}
into something what let me generate those 30 sets but with posts distributed among them using this pattern:
<!--First set should has post in order: --
<div class="set>
<div class="post twitter">{stuff}</div> {instagram post} {instagram post}
{instagram post}{instagram post}{twitter post}
</div> <!--//END set-->
<!--Second set order:-->
<div class="set">
{instagram} {instagram} {twitter}
{twitter} {instagram} {instagram}
</div>
etc.
Of course there is no guarantee that there would be enough post to create all 30 sets with those patterns so I need to create as many sets following those two patterns and leftovers put in sets as before simply in order they are pulled from db.
Thats all.
Thanks in advance for any suggestions / ready solutions ;) etc.
You could try something with a split between the two kind of posts using array_filter.
$posts = $stmt->fetchAll();
$twitterPosts = array_filter($posts, function($post){
return $post->source == "twitter";
});
$instagramPosts = array_filter($posts, function($post){
return $post->source == "instagram";
});
$set=1;
while(!empty($twitterPosts) && !empty($instagramPosts))
{
if($set%2 == 1)
{
$instagramPost1 = array_shift($instagramPosts);
$instagramPost2 = array_shift($instagramPosts);
$twitterPost1 = array_shift($twitterPosts);
}
else
{
$instagramPost1 = array_shift($instagramPosts);
$twitterPost1 = array_shift($twitterPosts);
$twitterPost2 = array_shift($twitterPosts);
}
/* display them */
if($set==6) {//your condition
echo '</div> <!--//END set-->';
$set=0;
}
$set++;
}
/* now one of them is empty, you can just display the other one */
if(!empty($twitterPosts))
/* Display all remaining twitter posts */
elseif(!empty($instagramPosts))
/* Display all remaining instagram posts */
Of course you should add validation that there is still something in the array between 2 array_shift.
I hope this helps !
EDIT : sorry I missed the condition for only 3 item per row, adding it now.
I´m developing a simple, but flexible content manager, and for the pages management i want to give the user the opportunity to organize the layout by dragging contents in the page, being able to make rows of content divided by two or three, just like a table.
The following image can illustrate what i have in mind:
The user can make a layout to have an static image in the left, and a text on the right, and at the bottom, he can place an image gallery showing the thumbnails.
Now, my question is about how to store and load the data in Mysql...
I have two Options:
1) With serialized data for the layout:
In the page´s table i can have a field that will store a serialized data for this layout, and then, i just need to unserialize and make a loop with this array to assemble the content.
The Array would be like that:
// Rows / divisions ...
$array[0]['q'] = 2;
$array[1]['q'] = 1;
// The content
$array[0]['c'][0]['t'] = 3; // 't' = type (3 = image)
$array[0]['c'][0]['i'] = 124; // 'i' = id to search for this data
$array[0]['c'][1]['t'] = 1; // 't' = type (1 = text)
$array[0]['c'][1]['i'] = 2; // Referencia ao ID do conteudo
$array[1]['c'][0]['t'] = 4; // 't' = type (4 = image gallery)
$array[1]['c'][0]['i'] = 9; // Referencia ao ID do conteudo
and the serialized data to store in DB:
a:2:{i:0;a:2:{s:1:"q";i:2;s:1:"c";a:2:{i:0;a:2:{s:1:"t";i:3;s:1:"i";i:124;}i:1;a:2:{s:1:"t";i:1;s:1:"i";i:2;}}}i:1;a:2:{s:1:"q";i:1;s:1:"c";a:1:{i:0;a:2:{s:1:"t";i:4;s:1:"i";i:9;}}}}
Or i have other option:
2) All in database:
Here i can make a table to store all the "component" links for the page, including the rows/divisions and than i can make a query to assemble the content;
The table would be something like that:
id -> component id
id_page -> page´s id
type -> component type, and 0 == row
value -> id reference to content or quantity of divisions for the rows
And the data would be stored like that:
id / id_page / type / value
1 / 1 / 0 / 2 --> the first row divided in two
2 / 1 / 3 / 124 --> the image
3 / 1 / 1 / 2 --> the text
4 / 1 / 4 / 9 --> the image gallery
So, what options do you guys would use to have a better performance or better management? Is this the best way to make what i want?
Sorry if i was not clear in some point.
Thank you so much!
When you need data or configurations previously saved for some element, its better to have it denormalized in a key value table.
element_id | serialized_data
performance wise you only need to index element_id and you will have a 1row hit for each element_id with the data on it.
Below I have a line of code where it states which Page a user is currently on out of the number of Total Pages.
<h1>CREATING QUESTIONS AND ANSWERS: SESSION (AAA) <?php echo $sessionMinus ?> OF <?php echo $_SESSION['initial_count'] ?></h1>
So for example the line could read this:
CREATING QUESTIONS AND ANSWERS: SESSION (AAA) 3 OF 3
Now the problem I have is that if the user is on the first page, it doesn't display the number 1. So instead of stating 1 OF 3 or 1 OF 5, it is stating 2 OF 3 or 2 OF 5.
So my question is that how can I get the first page to equal 1 OF ... when user accesses the first session (first page)?
Below is the current code:
if(isset($_POST['sessionNum'])){
//Declare my counter for the first time
$_SESSION['initial_count'] = $_POST['sessionNum'];
$_SESSION['sessionNum'] = $_POST['sessionNum'];
$_SESSION['sessionCount'] = 0;
}
else if ($_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
$_SESSION['sessionCount']++;
}
$sessionMinus = $_SESSION['sessionCount'];
$_SESSION['sessionNum'] is the total number of Sessions. So if it is 3 OF 5, then $_SESSION['sessionNum'] is 5.
if you want to build something like "Wizards" then in sessions you would store some data to keep track of user activity and general process, you say "if the user is in the first session ..." that's confusing, better say "if the user is in first step"
say you want to store in sessions, "user is in step 1 of 3 total steps", you would need
$_SESSION["user_track"] = array(
("current") => 1,
("next")=>2,
("total") => 3,
("previous") => 0
);
and a IF to check on every step
if($_SESSION["user_track"]["next"] != $GLOBAL_STEP){
/*
$GLOBAL_STEP , a integer you defined in the current step say its 2
and users next step matches 2 then he/she is on the correct step
*/
}else if($_SESSION["user_track"]["next"] == $_SESSION["user_track"]["total"]){
/*At the ending step*/
}else{
// couldn't proceed to next step, something went wrong
}
hope it helps
I would suggest :
to use the word 'page' or 'steps' instead of 'session', because 'session' is confusing with the $_SESSION array.
to use a simple GET parameter for current page/step (e.g. yourpage.php?step=X), where by default the step value would be 1.
I have got a feature on my website called 'View friends' that displays a hidden div containing a users friends. The only problem so far is I would like it so that it would show 7 members on each row for 3 rows so a total of 21 members on each page. I know I will have to round up NumOfMembers/21 giving me the pages needed. I just need some advice in how I should set up the pagination from when thee SQL query gets the total amount of friends. Any ideas?
The SQL-query should use the limit and offset parameters for pagination, depending on the page n you are on, like this:
SELECT .... LIMIT 21 OFFSET n*21
When handling the results, simply use the modulo operator for determining the lines and rows your current result has to be put in:
// where $i is the result number
$row = $i % 7;
$line = $i % 3;
You have 2 options:
First you can load everything from the php in one query and put all users in an array(content), and just display in pages!
content = [];
max = 21;
function handlePaginationClick(page, pagination_container) {
$('#MyContentArea').empty();
for(var i=0;i<max;i++) {
if(null!=content[(page*max)+i]) $('#MyContentArea').append(content[(page*max)+i]);
}
return false;
}
$("#News-Pagination").pagination(content.length, {
items_per_page:max,
callback:handlePaginationClick
});
you can use Jquery Pagination: https://github.com/gbirke/jquery_pagination#readme
for that.
Another approach is still using jquery pagination, but not load everything at once! then you must have same ajax call in the method 'handlePaginationClick' to pull all page information.