PHP.SU

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

Страниц (23): В начало « ... 15 16 17 18 19 20 21 [22] 23 »

> Найдено сообщений: 340
maragon Отправлено: 20 Февраля, 2011 - 01:44:36 • Тема: Class.mysql • Форум: Программирование на PHP

Ответов: 10
Просмотров: 572
Да это я и знал.. но не так применял. Хорошо
щас опробую!!
maragon Отправлено: 20 Февраля, 2011 - 00:13:51 • Тема: Class.mysql • Форум: Программирование на PHP

Ответов: 10
Просмотров: 572
class.mysql

---
CODE (htmlphp):
скопировать код в буфер обмена
  1.  
  2. <?php
  3. class MySQL {
  4.  
  5.    // SET THESE VALUES TO MATCH YOUR DATA CONNECTION
  6.    private $db_host    = "localhost";  // server name
  7.    private $db_user    = "root";       // user name
  8.    private $db_pass    = "";   // password
  9.    private $db_dbname  = "moymir";   // database name
  10.    private $db_charset = "cp1251";     // optional character set (i.e. utf8)
  11.    private $db_pcon    = false;        // use persistent connection?
  12.  
  13.    // class-internal variables - do not change
  14.    private $error_desc     = "";       // mysql error string
  15.    private $error_number   = 0;        // mysql error number
  16.    private $mysql_link     = 0;        // mysql link resource
  17.    private $sql            = "";       // mysql query
  18.    private $result;                    // mysql query result
  19.  
  20.    /**
  21.      * Determines if an error throws an exception
  22.      *
  23.      * @var boolean Set to true to throw error exceptions
  24.      */
  25.    public $ThrowExceptions = false;
  26.  
  27.    /**
  28.      * Constructor: Opens the connection to the database
  29.      *
  30.      * @param boolean $connect (Optional) Auto-connect when object is created
  31.      * @param string $database (Optional) Database name
  32.      * @param string $server   (Optional) Host address
  33.      * @param string $username (Optional) User name
  34.      * @param string $password (Optional) Password
  35.      * @param string $charset  (Optional) Character set
  36.      */
  37.  
  38.    function __construct($pcon=false, $server="", $username="", $password="", $database="", $charset="") {
  39.  
  40.        if ($pcon)                 $this->db_pcon    = true;
  41.        if (strlen($server)   > 0) $this->db_host    = $server;
  42.        if (strlen($username) > 0) $this->db_user    = $username;
  43.        if (strlen($password) > 0) $this->db_pass    = $password;
  44.        if (strlen($database) > 0) $this->db_dbname  = $database;
  45.        if (strlen($charset)  > 0) $this->db_charset = $charset;
  46.  
  47.        //
  48.        if (strlen($this->db_host) > 0 && strlen($this->db_user) > 0)
  49.        {
  50.            $this->Open();
  51.        }
  52.    }
  53.  
  54.    /**
  55.      * Connect to specified MySQL server
  56.      *
  57.      * @return boolean Returns TRUE on success or FALSE on error
  58.      */
  59.    private function Open()
  60.    {
  61.        $this->ResetError();
  62.  
  63.        // Open persistent or normal connection
  64.        if ($this->db_pcon) {
  65.            $this->mysql_link = @mysql_pconnect($this->db_host, $this->db_user, $this->db_pass);
  66.        } else {
  67.            $this->mysql_link = @mysql_connect ($this->db_host, $this->db_user, $this->db_pass);
  68.        }
  69.  
  70.        // Connect to mysql server failed?
  71.        if (! $this->IsConnected()) {
  72.            $this->SetError();
  73.            return false;
  74.        }
  75.        else // Connected to mysql server
  76.        {
  77.            //
  78.            // Select a database (if specified)
  79.            if (strlen($this->db_dbname) > 0) {
  80.                if (strlen($this->db_charset) == 0) {
  81.                    if (! $this->SelectDatabase($this->db_dbname)) {
  82.                        return false;
  83.                    } else {
  84.                        return true;
  85.                    }
  86.                } else {
  87.                    if (! $this->SelectDatabase($this->db_dbname, $this->db_charset)) {
  88.                        return false;
  89.                    } else {
  90.                        return true;
  91.                    }
  92.                }
  93.            } else {
  94.                return true;
  95.            }
  96.        }
  97.    }
  98.  
  99.    /**
  100.      * Executes the given SQL query and returns the result
  101.      *
  102.      * @param string $sql The query string
  103.      * @return (boolean, string, object, array with objects) result
  104.      */
  105.    public function Query($sql, $debug = false) {
  106.        $this->ResetError();
  107.        $this->sql    = $sql;
  108.        $this->result = @mysql_query($this->sql, $this->mysql_link);
  109.        // show debug info
  110.        if($debug) self::ShowDebugInfo("sql=".$this->sql);
  111.        // start the analysis
  112.        if (TRUE === $this->result) {   // simply result
  113.            $return = TRUE;         // successfully (for example: INSERT INTO ...)
  114.        }
  115.        else if (FALSE === $this->result)
  116.        {
  117.            $this->SetError();
  118.            if($debug)
  119.            {
  120.                self::ShowDebugInfo("error=".$this->error_desc);
  121.                self::ShowDebugInfo("number=".$this->error_number);
  122.            }
  123.            $return = FALSE;        // error occured (for example: syntax error)
  124.        }
  125.        else // complex result
  126.        {
  127.            switch (mysql_num_rows($this->result)){
  128.                case 0:
  129.                    $return = NULL; // return NULL rows
  130.                    break;
  131.                case 1: // return one row ...
  132.                    if(1 != mysql_num_fields( $this->result))
  133.                    $return = mysql_fetch_object($this->result);    // as object
  134.                    else
  135.                    {
  136.                        $row    = mysql_fetch_row($this->result);       // or as single value
  137.                        $return = $row[0];
  138.                    }
  139.                    break;
  140.                default:
  141.                    $return = array();
  142.                    while( $obj = mysql_fetch_object($this->result)) array_push($return, $obj);
  143.            }
  144.        }
  145.        return $return;
  146.    }
  147.  
  148.  
  149.    /**
  150.      * Determines if a valid connection to the database exists
  151.      *
  152.      * @return boolean TRUE idf connectect or FALSE if not connected
  153.      */
  154.    public function IsConnected() {
  155.        if (gettype($this->mysql_link) == "resource") {
  156.            return true;
  157.        } else {
  158.            return false;
  159.        }
  160.    }
  161.  
  162.    /**
  163.      * Selects a different database and character set
  164.      *
  165.      * @param string $database Database name
  166.      * @param string $charset (Optional) Character set (i.e. utf8)
  167.      * @return boolean Returns TRUE on success or FALSE on error
  168.      */
  169.    public function SelectDatabase($database, $charset = "") {
  170.        $return_value = true;
  171.        if (! $charset) $charset = $this->db_charset;
  172.        $this->ResetError();
  173.        if (! (mysql_select_db($database))) {
  174.            $this->SetError();
  175.            $return_value = false;
  176.        } else {
  177.            if ((strlen($charset) > 0)) {
  178.                if (! (mysql_query("SET CHARACTER SET '{$charset}'", $this->mysql_link))) {
  179.                    $this->SetError();
  180.                    $return_value = false;
  181.                }
  182.            }
  183.        }
  184.        return $return_value;
  185.    }
  186.  
  187.    /**
  188.      * Clears the internal variables from any error information
  189.      *
  190.      */
  191.    private function ResetError() {
  192.        $this->error_desc = '';
  193.        $this->error_number = 0;
  194.    }
  195.  
  196.    /**
  197.      *  Show debug info
  198.      */
  199.    static function ShowDebugInfo($string=""){
  200.        print "<br>--- ".$string." ---<br>\r\n";
  201.    }
  202.  
  203.    /**
  204.      * Sets the local variables with the last error information
  205.      *
  206.      * @param string $errorMessage The error description
  207.      * @param integer $errorNumber The error number
  208.      */
  209.    private function SetError($errorMessage = '', $errorNumber = 0) {
  210.        try {
  211.            // get/set error message
  212.            if (strlen($errorMessage) > 0) {
  213.                $this->error_desc = $errorMessage;
  214.            } else {
  215.                if ($this->IsConnected()) {
  216.                    $this->error_desc = mysql_error($this->mysql_link);
  217.                } else {
  218.                    $this->error_desc = mysql_error();
  219.                }
  220.            }
  221.            // get/set error number
  222.            if ($errorNumber <> 0) {
  223.                $this->error_number = $errorNumber;
  224.            } else {
  225.                if ($this->IsConnected()) {
  226.                    $this->error_number = @mysql_errno($this->mysql_link);
  227.                } else {
  228.                    $this->error_number = @mysql_errno();
  229.                }
  230.            }
  231.        } catch(Exception $e) {
  232.            $this->error_desc = $e->getMessage();
  233.            $this->error_number = -999;
  234.        }
  235.        if ($this->ThrowExceptions) {
  236.            throw new Exception($this->error_desc);
  237.        }
  238.    }
  239.  
  240.    /**
  241.      * Destructor: Closes the connection to the database
  242.      *
  243.      */
  244.    public function __destruct() {
  245.        $this->Close();
  246.    }
  247.    /**
  248.      * Close current MySQL connection
  249.      *
  250.      * @return object Returns TRUE on success or FALSE on error
  251.      */
  252.    public function Close() {
  253.        $this->ResetError();
  254.        $success = $this->Release();
  255.        if ($success) {
  256.            $success = @mysql_close($this->mysql_link);
  257.            if (! $success) {
  258.                $this->SetError();
  259.            } else {
  260.                unset($this->sql);
  261.                unset($this->result);
  262.                unset($this->mysql_link);
  263.            }
  264.        }
  265.        return $success;
  266.    }
  267.  
  268.    /**
  269.      * Frees memory used by the query results and returns the function result
  270.      *
  271.      * @return boolean Returns TRUE on success or FALSE on failure
  272.      */
  273.    public function Release() {
  274.        $this->ResetError();
  275.        if (! $this->result) {
  276.            $success = true;
  277.        } else {
  278.            $success = @mysql_free_result($this->result);
  279.            if (! $success) $this->SetError();
  280.        }
  281.        return $success;
  282.    }
  283.  
  284. }// end
  285. ?>
maragon Отправлено: 19 Февраля, 2011 - 22:37:20 • Тема: Class.mysql • Форум: Программирование на PHP

Ответов: 10
Просмотров: 572
А если перевести на наш --- Русский? Хорошо
maragon Отправлено: 19 Февраля, 2011 - 20:38:16 • Тема: Class.mysql • Форум: Программирование на PHP

Ответов: 10
Просмотров: 572
Вс еданные идут в массив ($gifts)
вытащить их можно просто $gifts->login;
Цикл For стоит..
maragon Отправлено: 19 Февраля, 2011 - 20:26:49 • Тема: Class.mysql • Форум: Программирование на PHP

Ответов: 10
Просмотров: 572
не понял Вас Однако
(Добавление)
$gifts=$db->Query($sql,1); =
--- sql=SELECT `mir_users`.`login`, `mir_users`.`pol`, `mir_gifts`.`gift`, `mir_gifts`.`id`, `mir_gifts`.`n`, `mir_gifts`.`date`, `mir_gifts`.`time`, `mir_online`.`status` FROM `mir_gifts` LEFT JOIN `mir_users` ON `mir_gifts`.`n`=`mir_users`.`n` LEFT JOIN `mir_online` ON `mir_online`.`n`=`mir_users`.`n` WHERE `mir_gifts`.`n2`='1' ORDER by id ASC LIMIT 4 ---

print_R($gifts) =
stdClass Object ( [login] => maragon [pol] => 1 [gift] => 17 [id] => 9 [n] => 1 [date] => 02.20.11 [time] => 00:38:42 [status] => 1 )
maragon Отправлено: 19 Февраля, 2011 - 20:22:06 • Тема: Class.mysql • Форум: Программирование на PHP

Ответов: 10
Просмотров: 572
У меня не выводит через цикл подарочкии.

PHP:
скопировать код в буфер обмена
  1. <!--- список подарков -->
  2. <?PHP
  3. $sql = "SELECT
  4.         `mir_users`.`login`,
  5.         `mir_users`.`pol`,
  6.         `mir_gifts`.`gift`,
  7.         `mir_gifts`.`id`,
  8.         `mir_gifts`.`n`,
  9.         `mir_gifts`.`date`,
  10.         `mir_gifts`.`time`,
  11.         `mir_online`.`status`
  12.                 FROM `mir_gifts`
  13.         LEFT JOIN `mir_users`
  14.                         ON `mir_gifts`.`n`=`mir_users`.`n`
  15.         LEFT JOIN `mir_online`
  16.                         ON `mir_online`.`n`=`mir_users`.`n`
  17.         WHERE
  18.                 `mir_gifts`.`n2`='1'
  19.                 ORDER by id ASC LIMIT 4";
  20. $gifts=$db->Query($sql);
  21. $num = count($gifts);
  22. if($num != 0){ ?>
  23. <br><div class="info-title">Подарки от пользователей сети <small>(<a href="gifts.php?n=<?PHP echo $pagen; ?>" style="text-decoration:none;">все</a>)</small></div>
  24. <div>
  25. <?PHP
  26. echo "<table align='center'><tr>";
  27. for($i = 0; $i < $num; $i++)  
  28. {
  29. ?>
  30. <td class="text">
  31. <img src="./images/gifts/<?PHP echo $gifts[$i]->gift; ?>.png" border="0" width="96" title="Подарок отправлен: <?PHP echo $gifts[$i]->date; ?> \ <?PHP echo $gifts[$i]->time; ?>"><br>
  32. <center>
  33. <small><a href="n<?PHP echo $gifts[$i]->n; ?>"><?PHP if($gifts[$i]->login != ""){ echo "".$gifts[$i]->login."";} else { echo "<b>ГОСТЬ</b>";}?></a>&nbsp;<?PHP if($gifts[$i]->pol == 1){ echo "<img src='./images/male.png' border='0' title='Парень'>"; } else { echo "<img src='./images/female.png' border='0' title='Девушка'>"; } ?></small><br>
  34. <?PHP if($gifts[$i]->status == 1){ echo "<div style='background:#07ae4e; color:#ffffff; width:60px;'><CENTER><small><small>ONLINE</small></small></CENTER>";} else { echo "<div style='background:#DDD; color:#000; width:60px;'><CENTER><small><small>OFFLINE</small></small></CENTER>";} ?>
  35. </center>
  36. </td>
  37. <td width="70"></td>
  38. <?
  39. }
  40. echo "</tr></table>";
  41.  }
  42.  ?>
  43. </div>
  44. <!--- ///список подарков -->


Ежели в базе кол-во подарков > 1, т.е 2 - то он выводит как надо.. как быть?
maragon Отправлено: 18 Февраля, 2011 - 23:36:05 • Тема: Объединение • Форум: Программирование на PHP

Ответов: 7
Просмотров: 367
2OrmaJever Благодарствую!
maragon Отправлено: 18 Февраля, 2011 - 23:16:55 • Тема: Объединение • Форум: Программирование на PHP

Ответов: 7
Просмотров: 367
{$error .= "$err19";} у меня сообщение вида :Не правильно указан город.
---
Скажем есть форма:
PHP:
скопировать код в буфер обмена
  1. <b>Город:</b>&nbsp;
  2. <select name="gorod">
  3. <option value="Город1">Город1</option>
  4. <option value="Город2">Город2</option>
  5. <option value="Город3">Город3</option>
  6. <option value="Город4">Город4</option>
  7. </select>

Нужна проверка на правильность ввода города.. дабы через html копию не подменили.
---
Ваш пример - ругается.
maragon Отправлено: 18 Февраля, 2011 - 23:09:14 • Тема: Объединение • Форум: Программирование на PHP

Ответов: 7
Просмотров: 367
Странно. не идет.
maragon Отправлено: 18 Февраля, 2011 - 22:58:46 • Тема: Объединение • Форум: Программирование на PHP

Ответов: 7
Просмотров: 367
if ($gorod != "1Город") {$error .= "$err19";}
if ($gorod != "2Город") {$error .= "$err19";}
if ($gorod != "3Город") {$error .= "$err19";}
if ($gorod != "4Город") {$error .= "$err19";}
Как обеденить в одну строку? как-то прям в угол забился)
maragon Отправлено: 17 Февраля, 2011 - 20:21:06 • Тема: Смайлы • Форум: Программирование на PHP

Ответов: 6
Просмотров: 344
$messagein = preg_replace(":Хихи:","<img src='./images/smiles/1.gif'>",$messagein);
выводит мне : Радость : - : лишние
maragon Отправлено: 17 Февраля, 2011 - 20:00:45 • Тема: Смайлы • Форум: Программирование на PHP

Ответов: 6
Просмотров: 344
Скажем вывожу данные из бд (в основном текст)


есть переменная $msgs['message'] с текстом: :Хихи:
- пробывал заменять хихи str_replace не получлось.
Т.е, вместо :Xихи: нужно вывести смайл.
Допоможить! Хм
maragon Отправлено: 16 Февраля, 2011 - 01:08:16 • Тема: Работа с фотками • Форум: SQL и Архитектура БД

Ответов: 1
Просмотров: 25
Порыска по форумам и включи смекалку.
В бд создаешь таблицу вида: id \ photo (далее можешь статусы и тд. если какая-то соц.сеть у тебя) - AUTO_INCREMENT
При загрузке заносишь данные в переменные и суешь в бд запросом.
CODE (SQL):
скопировать код в буфер обмена
  1. INSERT INTO `photos`(photo) VALUES('{$photo}')
maragon Отправлено: 15 Февраля, 2011 - 06:50:20 • Тема: Вопросы • Форум: Программирование на PHP

Ответов: 2
Просмотров: 201
Есть конструкция:
Switch($_GET['test']){
... include ...
}
Обязательно ли во внутрь делать default: include(""); ? (дабы скажем не подставили http://...)
Либо сделать проще методом $_GET['test'] и инклюдить?)
Закатив глазки
maragon Отправлено: 13 Февраля, 2011 - 19:16:13 • Тема: Функция по символам • Форум: Напишите за меня, пожалуйста

Ответов: 5
Просмотров: 66
А определение по словам сделать можно?
Допустим вместо тех: аааа я возьму обшионый - большой текст.. и слова будут переноситься не очень красиво)
пример:
я был в аф
рике
Ха-ха
(Добавление)
up!

Страниц (23): В начало « ... 15 16 17 18 19 20 21 [22] 23 »
Powered by PHP  Powered By MySQL  Powered by Nginx  Valid CSS  RSS

 
Powered by ExBB FM 1.0 RC1. InvisionExBB