За последние 24 часа нас посетили 62172 программиста и 1599 роботов. Сейчас ищут 855 программистов ...

Вопрос с mysqli_query

Тема в разделе "PHP и базы данных", создана пользователем krow7, 12 окт 2011.

  1. krow7

    krow7 Активный пользователь

    С нами с:
    12 авг 2009
    Сообщения:
    398
    Симпатии:
    0
    Адрес:
    из Азии
    Всем приветик.

    Я вот набросал для себя класс для работы с MySQL-базой через MySQLi-расширение:
    PHP:
    1. <?php
    2. class db
    3. {
    4.     private $conn;
    5.     private $error='';
    6.     private $host;
    7.     private $user;
    8.     private $pass;
    9.     private $db;
    10.     private $query='';
    11.     private $count=0;
    12.    
    13.     public static function check($var)
    14.     {
    15.         if((is_object($var)) && (get_class($var)==='db'))
    16.         {
    17.             return true;
    18.         }
    19.         else
    20.         {
    21.             return false;
    22.         }
    23.     }
    24.    
    25.     public function __construct()
    26.     {
    27.         if(func_num_args())
    28.         {
    29.             $array=array('', '', '', '', 0);
    30.             for($i=0; $i<count(func_get_args()); $i++)
    31.             {
    32.                 $array[$i]=func_get_arg($i);
    33.             }
    34.             $this->host=$array[0];
    35.             $this->user=$array[1];
    36.             $this->pass=$array[2];
    37.             $this->db=$array[3];
    38.             $c=(int)$array[4];
    39.             if($c===1)
    40.             {
    41.                 $this->connect();
    42.             }
    43.         }
    44.     }
    45.    
    46.     public function checkConn()
    47.     {
    48.         return $this->conn;
    49.     }
    50.    
    51.     public function getLastError()
    52.     {
    53.         if(isset($this->error))
    54.         {
    55.             return $this->error;
    56.         }
    57.         else
    58.         {
    59.             return false;
    60.         }
    61.     }
    62.    
    63.     public function connect()
    64.     {
    65.         if($this->conn)
    66.         {
    67.             mysqli_close($this->conn);
    68.         }
    69.         unset($this->conn);
    70.         unset($this->error);
    71.         $this->conn=@mysqli_connect($this->host, $this->user, $this->pass, $this->db);
    72.         return $this;
    73.     }
    74.    
    75.     public function close()
    76.     {
    77.         if($this->conn)
    78.         {
    79.             mysqli_close($this->conn);
    80.         }
    81.         unset($this->conn);
    82.     }
    83.    
    84.     public function execQuery()
    85.     {
    86.         if(func_num_args()===1)
    87.         {
    88.             $query=func_get_arg(0);
    89.         }
    90.         if(func_num_args()===0)
    91.         {
    92.             $query=$this->query;
    93.         }
    94.         if(!empty($query))
    95.         {
    96.             $result=mysqli_query($this->conn, trim($query));
    97.             if(mysqli_errno($this->conn))
    98.             {
    99.                 $this->error=mysqli_error($this->conn);
    100.             }
    101.             $this->count++;
    102.             return $result;
    103.         }
    104.         return false;
    105.     }
    106.    
    107.     public function printQuery()
    108.     {
    109.         if(func_num_args()===1)
    110.         {
    111.             $query=func_get_arg(0);
    112.         }
    113.         if(func_num_args()===0)
    114.         {
    115.             $query=$this->query;
    116.         }
    117.         if(!empty($query))
    118.         {
    119.             printf("<p>%s</p>", $query);
    120.         }
    121.         else
    122.         {
    123.             echo 'No query!';
    124.         }
    125.         return $this;
    126.     }
    127.    
    128.     public function select()
    129.     {
    130.         if(func_num_args())
    131.         {
    132.             $this->query="SELECT ";
    133.             foreach(func_get_args() as $arg)
    134.             {
    135.                 $arg=mysqli_real_escape_string($this->conn, $arg);
    136.                 $this->query.='`'.$arg.'`, ';
    137.             }
    138.             $this->query[strlen($this->query)-2]='';
    139.         }
    140.         return $this;
    141.     }
    142.    
    143.     public function insertInto()
    144.     {
    145.         if(func_num_args())
    146.         {
    147.             $this->query="INSERT INTO ";
    148.             foreach(func_get_args() as $arg)
    149.             {
    150.                 $arg=mysqli_real_escape_string($this->conn, $arg);
    151.                 $this->query.='`'.$arg.'`, ';
    152.             }
    153.             $this->query[strlen($this->query)-2]='';
    154.         }
    155.         return $this;
    156.     }
    157.  
    158.     public function values()
    159.     {
    160.         if(func_num_args())
    161.         {
    162.             $this->query.="VALUES (";
    163.             foreach(func_get_args() as $arg)
    164.             {
    165.                 $arg=mysqli_real_escape_string($this->conn, $arg);
    166.                 $this->query.="'".$arg."', ";
    167.             }
    168.             $this->query[strlen($this->query)-2]='';
    169.             $this->query[strlen($this->query)-1]='';
    170.             $this->query.=")";
    171.         }
    172.         return $this;
    173.     }
    174.    
    175.     public function fields()
    176.     {
    177.         if(func_num_args())
    178.         {
    179.             $this->query.="(";
    180.             foreach(func_get_args() as $arg)
    181.             {
    182.                 $arg=mysqli_real_escape_string($this->conn, $arg);
    183.                 $this->query.="`".$arg."`, ";
    184.             }
    185.             $this->query[strlen($this->query)-2]='';
    186.             $this->query[strlen($this->query)-1]='';
    187.             $this->query.=") ";
    188.         }
    189.         return $this;
    190.     }
    191. }
    192. ?>
    Теперь пытаюсь выполнить такой скрипт:
    PHP:
    1. <?php
    2. $file='allo mudak';
    3. include("class/db.php");
    4. $db=new db('servir', 'uzir', 'porol', 'baza', 1);
    5. $answer=$db
    6.     ->insertInto('downloads')
    7.     ->fields("ip", "time", "path")
    8.     ->values($_SERVER['REMOTE_ADDR'], time(), $file)
    9.     ->printQuery()
    10.     ->execQuery();
    11. echo $db->getLastError();
    12. ?>
    А мне в ответ:
    INSERT INTO `downloads` (`ip`, `time`, `path`) VALUES ('192.168.137.100', '1318438947', 'allo mudak')

    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1


    Сама кверя, формируемая методами, вроде бы верная (во всяком случае проверил в Navicat - запрос выполняется).

    Структура таблицы:
    [sql]CREATE TABLE `downloads` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `ip` varchar(255) DEFAULT NULL,
    `time` bigint(20) DEFAULT NULL,
    `path` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=cp1251;[/sql]

    Где я ошибся? Почему через Навик запрос выполняется, а средствами PHP - нет? Если нужны какие-либо другие характеристики - напишу.
     
  2. krow7

    krow7 Активный пользователь

    С нами с:
    12 авг 2009
    Сообщения:
    398
    Симпатии:
    0
    Адрес:
    из Азии
    оказалось, у меня не убирались лишние пробелы, причем гугл хром эти пробелы не выводил. запустил через оперу - все увидел и пофиксил. ДОЛБАНЫЙ ХРОМ.
     
  3. Gromo

    Gromo Активный пользователь

    С нами с:
    24 май 2010
    Сообщения:
    2.786
    Симпатии:
    2
    Адрес:
    Ташкент
    опера рулит :))
     
  4. tommyangelo

    tommyangelo Старожил

    С нами с:
    6 дек 2009
    Сообщения:
    2.549
    Симпатии:
    0
    Адрес:
    Мариуполь
    PHP:
    1.  
    2. <?php
    3. public function fields()
    4.      {
    5.          if(func_num_args())
    6.          {
    7.              $this->query.="(";
    8.              foreach(func_get_args() as $arg)
    9.              {
    10.                  $arg=mysqli_real_escape_string($this->conn, $arg);
    11.                  $this->query.="`".$arg."`, ";
    12.              }
    13.              $this->query[strlen($this->query)-2]='';
    14.              $this->query[strlen($this->query)-1]='';
    15.              $this->query.=") ";
    16.          }
    17.          return $this;
    18.      }
    А почему бы не так?

    PHP:
    1.  
    2. <?php
    3. public function fields()
    4.      {
    5.          $args = func_num_args();
    6.          if($args)
    7.          {
    8.              $this->query.="(`" . implode("`, `", $args) . "`)";
    9.          }
    10.          return $this;
    11.      }
     
  5. krow7

    krow7 Активный пользователь

    С нами с:
    12 авг 2009
    Сообщения:
    398
    Симпатии:
    0
    Адрес:
    из Азии
    tommyangelo
    кстати, да!
    спасибо большое
    про имплод даже что-то и не подумал.
    + не надо возиться с запятой в конце.
     
  6. tommyangelo

    tommyangelo Старожил

    С нами с:
    6 дек 2009
    Сообщения:
    2.549
    Симпатии:
    0
    Адрес:
    Мариуполь
    krow7
    Я когда-то тож возился, пока не подсказали)

    А еще в классе смутило, что нельзя изменить порядок вызова методов.

    Имхо, правильнее будет сохранять значения во внутренние переменные, а запрос лепить непосредственно перед выполнением.
     
  7. krow7

    krow7 Активный пользователь

    С нами с:
    12 авг 2009
    Сообщения:
    398
    Симпатии:
    0
    Адрес:
    из Азии
    tommyangelo
    хм, как-то даже не задумывался над порядком. теперь интересно стало - перепишу ;)
    еще раз спасибо за ценные советы.
     
  8. tommyangelo

    tommyangelo Старожил

    С нами с:
    6 дек 2009
    Сообщения:
    2.549
    Симпатии:
    0
    Адрес:
    Мариуполь
    krow7
    У меня как раз недавно была ситуация - в зависимости от определенных условий запрос менялся.

    Т.е. в начале экшена сделал "основу" запроса - указал таблицу, набор извлекаемых полей, сортировку.
    А потом в зависимости от фильтров добавлял различные where и order

    Так что произвольный порядок бывает нужен.
     
  9. topas

    topas Активный пользователь

    С нами с:
    16 авг 2006
    Сообщения:
    2.258
    Симпатии:
    36
    tommyangelo
    array_walk или array_map забыли для mysq_real_escape_string
     
  10. krow7

    krow7 Активный пользователь

    С нами с:
    12 авг 2009
    Сообщения:
    398
    Симпатии:
    0
    Адрес:
    из Азии
    topas
    когда уже в класс дописывал - прицепил ;)