In my recent post: Google AdSense Now Logs Into Your Sites I mentioned that displaying a quick preview of your content might be useful in some scenarios. В моих последних поста: Google AdSense сейчас бревен в своих сайтов я уже упоминал, что отображение быстро просматривать содержание может оказаться полезным в некоторых сценариях. Particularly if you want to charge subscription fees for full content. I’ll illustrated with an example so you can get an idea of where to start in accomplishing this with your own sites. Особенно, если вы хотите взимать плату за подписку полное содержание. Я проиллюстрирована примером, чтобы вы могли получить представление о том, с чего начать при выполнении этого с вашего собственного сайта. The key component in making this work is the substr ($content,0,300) function. Ключевым компонентом в обеспечении этой работы SUBSTR ($ содержании, 0300) функции. You specify the length of content by declaring a start (0) and the end (300). Вы указываете длину содержания, объявив начало (0) и конца (300). You can then output a shortened version of $content and store it in a separate variable. Затем Вы можете вывод сокращенный вариант долл. содержание и храните его в отдельную переменную. Great to use as a “preview” for your content. Великий использовать в качестве "Предварительный просмотр" для вашего содержания. Note: the number refers to the numbers of characters in the provided string, not words. Примечание: число указывает на количество символов в строке при условии, а не словами.

What you need to do is figure out the existing variables you’re outputting on each content page (likely found within your template). Что нужно сделать, это выяснить существующие переменные вы выводит на каждой странице содержания (вероятно, найти в шаблоне). This part goes beyond the scope of this article. Эта часть выходит за рамки данной статьи. All sites are set up with slightly differently variables and even grab content from different sources…this is not an exact science. Все сайты создаются с несколько разным переменным, и даже захватить содержание из разных источников ... это не точная наука.

I will assume your data is coming from a mySQL database and $id is a number that refers to a row of content in your database. Я буду выполнять ваши данные из базы данных MySQL и $ ID представляет собой число, которое ссылается на строку из содержания в вашей базе данных. This first snippet shows a row being queried in preparation for it to be cut down into a preview. Этот первый фрагмент показывает строку время сомнение в подготовке к ее сокращению на просмотр.

  1. $result = mysql_query ( "SELECT id,content FROM table WHERE id={$id}" , $db ) ;
  2. $row = mysql_fetch_row ( $result ) ;
  3. echo $row [ 0 ] ; //The value of id
  4. echo $row [ 1 ] ; //The value of content
  5. $content = $row [ 1 ] ; //Store it into something we can identify easily

This is even easier when you already have your content in a string. Это даже проще, если у вас уже есть ваше содержание в строку. In that case you wouldn’t have to run a query on it again. В этом случае вам не придется запускать запрос на нее еще раз. There are also applications in which you would want to have this preview show before you content. Существуют также приложения, в которых вы хотели бы иметь эту прослушать, прежде чем показать содержимое. In that case you would only need to integrate something like this into your templates (and yes there is more then one way to do this): В этом случае вам будет нужно всего лишь включить нечто подобное в ваши шаблоны (да и есть более чем один из способов это сделать):

  1. $previewcontent = substr ( $content , 0 , 300 ) ;
  2. if ( isset ( $go ) ) { //If set then they have seen the preview already
  3. echo $content ; //Display your usual content
  4. } else { //First time viewing this page
  5. echo "Article preview:<br><br>" . $previewcontent ;
  6. echo "See this entire post<a href= \" showcontent.php?id=" . $id . "&go=yes \" >here</a>" ;
  7. //Or you could add something like this (instead of lines 6 & 7) for paid/subscription content
  8. if ( isset ( $user ) ) { //If a user is logged in…
  9. echo "Go ahead and <a href= \" showcontent.php?id=" . $id . "&go=yes \" >view</a>" ;
  10. } else { //$user is not set - insert login/signup link/form below
  11. echo "To view this solution please click <a href= \" yoursignupscript.php \" >here</a> to purchase access." ;
  12. }

In my alternate configuration where visitors need to purchase access you should also change your first if statement to check if a user is logged in by doing: В моих заместителей конфигурации, где посетителям необходимо купить доступ вы должны также изменить ваш первый том случае, если заявление, чтобы проверить, если пользователю войти в систему, выполнив:
if(isset($go) && isset($user)) если (isset ($ го) И И isset ($ пользователя))

There’s some security and usability you need to consider when implementing this which I didn’t get into. Там-то безопасность и удобство использования нужно учитывать при осуществлении данной которых я не попасть. As shown above isset () is another very handy function in php as it allows you to set triggers in conjunction with if statements. Как показано выше, isset () это еще одна очень удобная функция в PHP, как оно позволяет устанавливать триггеры в том случае, если одновременно с заявлениями. This can make a webpage very dynamic. Это может сделать веб-страницу весьма динамичным.

If you’re not that far yet with a coding language, I hope this at least gives you some ideas of what you can do. For additional help check out php.net: http://us3.php.net/substr . Если вы не в том, что далеко еще с кодированием языка, я надеюсь, что это по крайней мере, дает вам некоторые идеи о том, что вы можете сделать. Для получения дополнительной информации посетите php.net: http://us3.php.net/substr. Just getting started with php/mySQL?: Increase Earning Potential With These PHP/mySQL Tutorials Просто знакомитесь с PHP / MySQL?: Увеличение прибыли с этими PHP / MySQL Обучение



Leave A Comment: Оставить комментарий:

Comments RSS Feed Комментарии RSS канал

5 Minus 2 = минус 2 =

Custom Theme by Rob Malon | Content & Design © 2008 - Rob Malon [dot] Com. Пользовательские темы Боб Malon | Содержание И Дизайн © 2008 - Боб Malon [точка] Ком. "));
"));