{"title":"PHP MySQL数据库操作类:连接、字符集设置、SQL执行检测","description":"本文介绍了一个PHP类,用于连接MySQL数据库,设置字符集,并执行SQL语句。类中提供了连接、字符集设置和SQL执行检测的方法,并解释了如何使用该类进行数据库操作。","keywords":"PHP, MySQL, 数据库, 连接, 字符集, SQL, 执行, 检测, 类","content":"<?php\nclass sql\n{\n public $host;\n public $port;\n public $user;\n public $pass;\n public $db;\n public $charset;\n //数据库初始化\n public function __construct(array $config = array())\n {\n $this->host = $config['host'] ?? '127.0.0.1';\n $this->port = $config['port'] ?? '3306';\n $this->user = $config['user'] ?? 'roo1t';\n $this->pass = $config['pass'] ?? '123456';\n $this->db = $config['db'] ?? 'test';\n $this->charset = $config['charset'] ?? 'utf8';\n }\n //数据库链接认证\n public $link;\n public $errno;\n public $error;\n public function connect()\n {\n $this->link = @mysqli_connect($this->host, $this->user, $this->pass, $this->db, $this->port);\n if (!$this->link) {\n $this->errno = mysqli_connect_errno();\n $this->error = iconv('gbk', 'utf-8', mysqli_connect_error());\n return false;\n }\n\n return true;\n }\n //数据库字符集设置\n public function charset()\n {\n $res = mysqli_set_charset($this->link, $this->charset);\n\n //判断是否成功\n if (!$res) {\n $this->errno = mysqli_errno($this->link);\n $this->error = mysqli_error($this->link);\n return false;\n }\n return true;\n }\n //sql执行检测\n public function check($sql)\n {\n $res = mysqli_query($this->link, $sql);\n //判断是否成功\n if (!$res) {\n $this->errno = mysqli_errno($this->link);\n $this->error = mysqli_error($this->link);\n return 'false';\n }\n return $res;\n }\n}\n\n\n$db = array(\n 'host' => '127.0.0.1',\n 'port' => '3306',\n 'user' => '123456',\n 'pass' => '123456',\n 'db' => '123456',\n 'charset' => 'utf8'\n);\n$db = new sql($db);\necho $db->connect();\n这段代码 为什么不能写入 echo $db->check("INSERT INTO 'user' ('user') values ('123')");\n内容:The code cannot write the echo $db->check("INSERT INTO 'user' ('user') values ('123')") statement because there is a syntax error in the SQL query. \n\nThe correct syntax for inserting values into a table is as follows:\n\nINSERT INTO table_name (column1, column2, column3, ...)\nVALUES (value1, value2, value3, ...);\n\nIn your case, the query should be:\n\n$db->check("INSERT INTO user (user) VALUES ('123')");\n\nNote that the table name and column name should be enclosed in backticks (`) instead of single quotes (').\n\nOnce you fix the syntax error, the query should execute successfully.\n&quot

PHP MySQL数据库操作类:连接、字符集设置、SQL执行检测

原文地址: https://www.cveoy.top/t/topic/qinB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录