PHP.SU

Программирование на PHP, MySQL и другие веб-технологии
PHP.SU Портал     На главную страницу форума Главная     Помощь Помощь     Поиск Поиск     Поиск Яндекс Поиск Яндекс     Вакансии  Пользователи Пользователи

Страниц (16): В начало « ... 8 9 10 11 12 13 14 15 [16]

> Найдено сообщений: 232
Ammiak Отправлено: 11 Мая, 2011 - 07:45:50 • Тема: передача параметров из нескольких форм • Форум: JavaScript & VBScript

Ответов: 4
Просмотров: 1559
всем привет!
есть 2 формы:
CODE (html):
скопировать код в буфер обмена
  1.  
  2. <form id="form1" method="post" action="../php/script1.php">
  3. <input id="in1" name="in1" value="old_parameter1"/>
  4. <input id="in2" name="in2" value="old_parameter2"/>
  5. <input id="in3" name="in3" value="old_parameter3"/>
  6. <input type="submit" id="subm1" />
  7. </form>
  8.  
  9. <form id="form2" method="post" action="../php/script2.php">
  10. <input id="in4" name="in4" value="new_parameter"/>
  11. <input type="submit" id="subm2" />
  12. </form>
  13.  

нужно в script2.php передать параметры из form1. Пробовал аяксом собрать параметры и отправить скрипту:
CODE (javascript):
скопировать код в буфер обмена
  1.  
  2. $(function() {
  3. $('#subm2').click(function(e) {
  4. e.preventDefault();
  5. var a=$('#form1').serialize();
  6. $.post("../php/script2.php", a)
  7. });
  8. });
  9.  

но пар-ры не передались, подскажите пожал. как сделать? заранее благодарю
(Добавление)
кто-нибудь?
Ammiak Отправлено: 04 Мая, 2011 - 11:48:46 • Тема: вывод значений из бд • Форум: SQL и Архитектура БД

Ответов: 3
Просмотров: 27
переделал так, результат тот же (поправьте если что-то не так):

CODE (javascript):
скопировать код в буфер обмена
  1.  
  2. $(':submit').click(function(e) {
  3. e.preventDefault();
  4. var obj = $(this);
  5. ajax_sum(obj);
  6. });
  7.  
  8. function ajax_sum(elem) {
  9. $(':submit').each(function() {
  10. var a=$(elem).prev().val();
  11. $.post('../php/script.php', {good2:sd}, function(data) {
  12. if (data.length>0) {
  13. $('#total').html(data).show();
  14. }
  15. })
  16. });
  17. }
  18.  

(Добавление)
По-моему, аякс здесь ни при чём, пробовал без него:

CODE (html):
скопировать код в буфер обмена
  1.  
  2. <form method="post" action="../php/script.php">
  3. <input id="good1" name="good1"  type="hidden" value="Товар1"><a href="#">Товар1</a></input>
  4. <input type="submit" id="subm1" class="basket" value="" title="Добавить в корзину"/><br>
  5.  
  6. <input id="good2" name="good2"  type="hidden" value="Товар2"><a href="#">Товар2</a></input>
  7. <input type="submit" id="subm2" class="basket" value="" title="Добавить в корзину" /><br>
  8.  


PHP:
скопировать код в буфер обмена
  1.  
  2. $good = $_POST['good2'];
  3.  
  4. $query = mysql_query("select type_good, price_good from goods where type_good LIKE '%$good%'");
  5.  
  6. $row = mysql_fetch_assoc($query);
  7. print_r($row);
  8.  


Всё равно в итоге:

Цитата:

[type_good] => Товар1 [price_good] => цена
Ammiak Отправлено: 04 Мая, 2011 - 09:50:08 • Тема: вывод значений из бд • Форум: SQL и Архитектура БД

Ответов: 3
Просмотров: 27
здравствуйте, помогите разобраться: есть форма заказа:
CODE (html):
скопировать код в буфер обмена
  1.  
  2. <form method="post" action="../php/script.php">
  3. <input id="good1" name="good1"  type="hidden" value="Товар1"><a href="#">Товар1</a></input>
  4. <input type="submit" id="subm1" class="basket" value="" title="Добавить в корзину"/><br>
  5.  
  6. <input id="good2" name="good2"  type="hidden" value="Товар2"><a href="#">Товар2</a></input>
  7. <input type="submit" id="subm2" class="basket" value="" title="Добавить в корзину" /><br>
  8.  
  9. <input id="good3" name="good3"  type="hidden" value="Товар3"><a href="#">Товар3</a></input>
  10. <input type="submit" id="subm2" class="basket" value="" title="Добавить в корзину" /><br>
  11.  
  12. <input id="good4" name="good4"  type="hidden" value="Товар4"><a href="#">Товар4</a></input>
  13. <input type="submit" id="subm2" class="basket" value="" title="Добавить в корзину" /><br>
  14.  
  15. <input id="good5" name="good5"  type="hidden" value="Товар5"><a href="#">Товар5</a></input>
  16. <input type="submit" id="subm2" class="basket" value="" title="Добавить в корзину" />
  17.  
  18. <span id="total"> </span>
  19. </form>
  20.  


затем немного ajax

CODE (javascript):
скопировать код в буфер обмена
  1.  
  2. $(function() {
  3. $('#total').slideUp();
  4. $(':submit').click(function(e) {
  5. e.preventDefault();
  6. ajax_sum();
  7. });
  8.  
  9. function ajax_sum() {
  10. $(':submit').each(function() {
  11. var a=$(this).prev().val();
  12. $.post('../php/script.php', {good2:a}, function(data) {
  13. if (data.length>0) {
  14. $('#total').html(data).show();
  15. }
  16. })
  17. });
  18. }
  19.  
  20. });
  21.  


скрипт обработки script.php:
PHP:
скопировать код в буфер обмена
  1.  
  2. $good = $_POST['good2'];
  3.  
  4. $query = mysql_query("select type_good, price_good from goods where type_good LIKE '%$good%'");
  5.  
  6. $row = mysql_fetch_assoc($query);
  7. echo '<table><tr><td>'.$row['type_good'].'</td><td>'.$row['price_good'].'</td></tr></table>';
  8.  


При нажатии на кнопку "Добавить в корзину" значение инпута, соответствующего этой кнопке отправляется в бд, где есть столбцы type_good (название товара) и price_good (его цена). Если соответствие найдено, в <span id="total"> помещается название товара и цена.
У меня при нажатии на второй сабмит возвращается название и цена первого товара из списка а не второго, да и проверял дамп массива $row, выглядит так:
Цитата:

[type_good] => Товар1 [price_good] => цена


как добиться соответствия? заранее благодарю
Ammiak Отправлено: 22 Апреля, 2011 - 10:53:00 • Тема: rss и прокси-сервер • Форум: Программирование на PHP

Ответов: 1
Просмотров: 732
Здравствуйте, есть парсер новостей import.php:

PHP:
скопировать код в буфер обмена
  1.  
  2. // Подключаем класс lastRSS и настройки прокси
  3. include_once "lastRSS.php";
  4. include_once "news_curl.php";
  5.  
  6. // новый экземпляр класса
  7. $rss = new lastRSS;
  8.  
  9. $rss_import = array(
  10.     'http://news.sportbox.ru/taxonomy/term/7212/0/feed'
  11.  );
  12.  
  13.  // выводим все RSS-файлы из списка
  14. foreach ($rss_import as $url) {
  15.  
  16.      if ($chan = $rss->get($url)) {
  17.      
  18.         // выводим заголовок и ссылку канала
  19.         echo "<h1><a href=$chan[link]>$chan[title]</a></h1>";
  20.        
  21.         // выводим описание канала
  22.        echo "<p><h2>$chan[description]</h2>";
  23.                    
  24.        // выводим статьи
  25.        foreach ($chan['items'] as $item)
  26.        {
  27.        
  28.                  echo "<span><a href=$item[link]>$item[title]</a></span><br><br>";
  29.      
  30.            }
  31.      }
  32.     else {
  33.         echo "Ошибочка! Пустой канал или неправильный формат
  34.              файла <br>$url\n<br>";
  35.     }
  36.  
  37. }
  38.  


к нему файл с настройками прокси-сервера news_curl.php:

PHP:
скопировать код в буфер обмена
  1.  
  2. $curl=curl_init("http://news.sportbox.ru/taxonomy/term/7212/0/feed");
  3. $proxy='user:password@IP:port';
  4.  
  5. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
  6. curl_setopt($curl, CURLOPT_PROXY, $proxy);
  7.  


и класс lastRSS.php:

PHP:
скопировать код в буфер обмена
  1.  
  2. class lastRSS {
  3.        
  4.         var $default_cp = 'UTF-8';
  5.         var $CDATA = 'nochange';
  6.         var $cp = '';
  7.         var $items_limit = 0;
  8.         var $stripHTML = False;
  9.         var $date_format = '';
  10.  
  11.         var $channeltags = array ('title', 'link', 'description', 'language', 'copyright', 'managingEditor', 'webMaster', 'lastBuildDate', 'rating', 'docs');
  12.         var $itemtags = array('title', 'link', 'description', 'author', 'category', 'comments', 'enclosure', 'guid', 'pubDate', 'source');
  13.         var $imagetags = array('title', 'url', 'link', 'width', 'height');
  14.         var $textinputtags = array('title', 'description', 'name', 'link');
  15.  
  16.                 function Get ($rss_url) {
  17.                 // If CACHE ENABLED
  18.                 if ($this->cache_dir != '') {
  19.                         $cache_file = $this->cache_dir . '/rsscache_' . md5($rss_url);
  20.                         $timedif = @(time() - filemtime($cache_file));
  21.                         if ($timedif < $this->cache_time) {
  22.                                 // cached file is fresh enough, return cached array
  23.                                 $result = unserialize(join('', file($cache_file)));
  24.                                 // set 'cached' to 1 only if cached file is correct
  25.                                 if ($result) $result['cached'] = 1;
  26.                         } else {
  27.                                 // cached file is too old, create new
  28.                                 $result = $this->Parse($rss_url);
  29.                                 $serialized = serialize($result);
  30.                                 if ($f = @fopen($cache_file, 'w')) {
  31.                                         fwrite ($f, $serialized, strlen($serialized));
  32.                                         fclose($f);
  33.                                 }
  34.                                 if ($result) $result['cached'] = 0;
  35.                         }
  36.                 }
  37.                 // If CACHE DISABLED >> load and parse the file directly
  38.                 else {
  39.                         $result = $this->Parse($rss_url);
  40.                         if ($result) $result['cached'] = 0;
  41.                 }
  42.                 // return result
  43.                 return $result;
  44.         }
  45.        
  46.                 function my_preg_match ($pattern, $subject) {
  47.                 preg_match($pattern, $subject, $out);
  48.  
  49.                         if(isset($out[1])) {
  50.                        
  51.                         if ($this->CDATA == 'content') { // Get CDATA content (without CDATA tag)
  52.                                 $out[1] = strtr($out[1], array('<![CDATA['=>'', ']]>'=>''));
  53.                         } elseif ($this->CDATA == 'strip') { // Strip CDATA
  54.                                 $out[1] = strtr($out[1], array('<![CDATA['=>'', ']]>'=>''));
  55.                         }
  56.  
  57.                        
  58.                         if ($this->cp != '')
  59.                                 //$out[1] = $this->MyConvertEncoding($this->rsscp, $this->cp, $out[1]);
  60.                                 $out[1] = iconv($this->rsscp, $this->cp.'//TRANSLIT', $out[1]);
  61.                         // Return result
  62.                         return trim($out[1]);
  63.                 } else {
  64.                
  65.                         return '';
  66.                 }
  67.         }
  68.  
  69.        
  70.         function unhtmlentities ($string) {
  71.                 // Get HTML entities table
  72.                 $trans_tbl = get_html_translation_table (HTML_ENTITIES, ENT_QUOTES);
  73.                 // Flip keys<==>values
  74.                 $trans_tbl = array_flip ($trans_tbl);
  75.                 // Add support for &apos; entity (missing in HTML_ENTITIES)
  76.                 $trans_tbl += array('&apos;' => "'");
  77.                 // Replace entities by values
  78.                 return strtr ($string, $trans_tbl);
  79.         }
  80.  
  81.        
  82.         function Parse ($rss_url) {
  83.                 // Open and load RSS file
  84.                 if ($f = @fopen($rss_url, 'r')) {
  85.                         $rss_content = '';
  86.                         while (!feof($f)) {
  87.                                 $rss_content .= fgets($f, 4096);
  88.                         }
  89.                         fclose($f);
  90.  
  91.                         $result['encoding'] = $this->my_preg_match("'encoding=[\'\"](.*?)[\'\"]'si", $rss_content);
  92.                         // if document codepage is specified, use it
  93.                         if ($result['encoding'] != '')
  94.                                 { $this->rsscp = $result['encoding']; } // This is used in my_preg_match()
  95.                        
  96.                         else
  97.                                 { $this->rsscp = $this->default_cp; } // This is used in my_preg_match()
  98.  
  99.                         preg_match("'<channel.*?>(.*?)</channel>'si", $rss_content, $out_channel);
  100.                         foreach($this->channeltags as $channeltag)
  101.                         {
  102.                                 $temp = $this->my_preg_match("'<$channeltag.*?>(.*?)</$channeltag>'si", $out_channel[1]);
  103.                                 if ($temp != '') $result[$channeltag] = $temp; // Set only if not empty
  104.                         }
  105.                         if ($this->date_format != '' && ($timestamp = strtotime($result['lastBuildDate'])) !==-1) {
  106.                         $result['lastBuildDate'] = date($this->date_format, $timestamp);
  107.                         }
  108.  
  109.                         preg_match("'<textinput(|[^>]*[^/])>(.*?)</textinput>'si", $rss_content, $out_textinfo);
  110.                                
  111.                                 // Look for tag <textinput> with or without any attributes, but skip truncated version <textinput /> (it's not beggining tag)
  112.                         if (isset($out_textinfo[2])) {
  113.                                 foreach($this->textinputtags as $textinputtag) {
  114.                                         $temp = $this->my_preg_match("'<$textinputtag.*?>(.*?)</$textinputtag>'si", $out_textinfo[2]);
  115.                                         if ($temp != '') $result['textinput_'.$textinputtag] = $temp; // Set only if not empty
  116.                                 }
  117.                         }
  118.                        
  119.                         preg_match("'<image.*?>(.*?)</image>'si", $rss_content, $out_imageinfo);
  120.                         if (isset($out_imageinfo[1])) {
  121.                                 foreach($this->imagetags as $imagetag) {
  122.                                         $temp = $this->my_preg_match("'<$imagetag.*?>(.*?)</$imagetag>'si", $out_imageinfo[1]);
  123.                                         if ($temp != '') $result['image_'.$imagetag] = $temp; // Set only if not empty
  124.                                 }
  125.                         }
  126.                        
  127.                         preg_match_all("'<item(| .*?)>(.*?)</item>'si", $rss_content, $items);
  128.                         $rss_items = $items[2];
  129.                         $i = 0;
  130.                         $result['items'] = array();
  131.                         foreach($rss_items as $rss_item) {
  132.                                
  133.                                 if ($i < $this->items_limit || $this->items_limit == 0) {
  134.                                         foreach($this->itemtags as $itemtag) {
  135.                                                 $temp = $this->my_preg_match("'<$itemtag.*?>(.*?)</$itemtag>'si", $rss_item);
  136.                                                 if ($temp != '') $result['items'][$i][$itemtag] = $temp; // Set only if not empty
  137.                                         }
  138.                                        
  139.                                         if ($this->stripHTML && $result['items'][$i]['description'])
  140.                                                 $result['items'][$i]['description'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['description'])));
  141.                                        
  142.                                         if ($this->stripHTML && $result['items'][$i]['title'])
  143.                                                 $result['items'][$i]['title'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['title'])));
  144.                                                 if ($this->date_format != '' && ($timestamp = strtotime($result['items'][$i]['pubDate'])) !==-1) {
  145.                                                
  146.                                                 $result['items'][$i]['pubDate'] = date($this->date_format, $timestamp);
  147.                                         }
  148.                                         $i++;
  149.                                 }
  150.                         }
  151.  
  152.                         $result['items_count'] = $i;
  153.                         return $result;
  154.                 }
  155.                 else
  156.                 {
  157.                         return False;
  158.                 }
  159.         }
  160. }
  161.  


Не работает с использованием прокси-сервера, выдаёт ошибку:

Цитата:

Notice: Undefined property: lastRSS::$cache_dir in E:\my_projects\lastRSS.php on line 58


т.е. ругается на строчку

Цитата:

if ($this->cache_dir != '') {


подскажите пожал. что я здесь неправильно подключил? (без прокси парсер работает нормально)
Ammiak Отправлено: 18 Апреля, 2011 - 16:05:01 • Тема: функция array_count_values() • Форум: Программирование на PHP

Ответов: 4
Просмотров: 318
Viper пишет:
$new = array();
foreach ($arr as $key=>$val) {
if ($key['Tue']) $new[] = $val;
}
echo count($new);

спс, то что надо
Ammiak Отправлено: 18 Апреля, 2011 - 14:44:46 • Тема: функция array_count_values() • Форум: Программирование на PHP

Ответов: 4
Просмотров: 318
Дамп массива выглядит так:
Цитата:
Array
(
[Mon] => 4
[Thu] => 2
[Tue] => 3
)

вопрос в следующем: как вывести скажем "Понедельников: 4".
Не так же:
PHP:
скопировать код в буфер обмена
  1. echo 'Понедельников:'. $value[0];

больше пока в голову ничего не приходит...
Ammiak Отправлено: 18 Апреля, 2011 - 13:10:53 • Тема: функция array_count_values() • Форум: Программирование на PHP

Ответов: 4
Просмотров: 318
здравствуйте, непонятен такой момент при использовании функции array_count_values(). Например обрабатываем такой массив:
PHP:
скопировать код в буфер обмена
  1.  
  2. $arr=array('Mon', 'Thu', 'Mon', 'Tue', 'Tue', 'Tue',  'Thu');
  3. foreach($a as $key=>$value)
  4. echo "$key=$value</br>";
  5.  


почему выводится только:
Цитата:
Tue=3
. заранее благодарю

Страниц (16): В начало « ... 8 9 10 11 12 13 14 15 [16]
Powered by PHP  Powered By MySQL  Powered by Nginx  Valid CSS  RSS

 
Powered by ExBB FM 1.0 RC1. InvisionExBB