我正在使用 php 并尝试使用 pdo 连接到 mysql。我读到我必须首先拥有 pdo 扩展名(不知道我是否这样做,也不知道如何检查它)。我已将 phpmyadmin 的 config.inc.php 文件更改为大声外部连接。看起来像这样:
<?php
/* Servers configuration */
$i = 0;
/* Server: localhost [1] */
$i++;
$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '8000';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'http';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'http'; ////I've also try with config here
$cfg['Servers'][$i]['user'] = 'xxxx';
$cfg['Servers'][$i]['password'] = 'xxxxx';
$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true;
?>
我的php文件是这样的:
function connect() {
global $pdo;
$pdo = new PDO("mysql:host=localhost:8000;dbname=sakila", "xxxx", "xxxxxx");
}
function get_actors_by_last_name($letter){
global $pdo;
$stmt = $pdo->prepare('
SELECT actor_id, first_name, get_actors_by_last_name
from actor
where first_name like :letter
limit 50');
$stmt->execute( array(':letter' => $letter . '%' ));
return $stmt->fetchAll( PDO::FETCH_OBJ);
}
?>
该页面是一个简单的表单,应该根据 Actor 名字的第一个字母来显示 Actor 的名字。每次您尝试使其在加载时页面库存正常工作时,不会给我带来任何东西,不是问题或异常。如果我更改主机参数并输入使用我的 mysql 的主机名值(在实际代码中为实际主机值):
$pdo = new PDO("mysql:host=mysql.value;dbname=sakila", "xxxx", "xxxxxx");
我收到一条消息:
fatal error :在/Users/josecarro/Desktop/jquery/ajax/dataBase/functions 中未捕获异常“PDOException”,消息为“SQLSTATE[HY000] [1130] 主机“x.x.x.x”不允许连接到此 MySQL 服务器” .php:13 堆栈跟踪: #0/Users/josecarro/Desktop/jquery/ajax/dataBase/functions.php(13): PDO->__construct('mysql:host=MacB...', 'xxxx', ' xxxx', NULL) #1/Users/josecarro/Desktop/jquery/ajax/dataBase/index.php(7): connect() #2 {main} 抛出/Users/josecarro/Desktop/jquery/ajax/dataBase/functions.php 第 13 行
这让我相信 pdo 扩展实际上正在工作。 要打开服务器并在我的文件所在目录的终端上使用此行:
open http://localhost:8000 && python -m SimpleHTTPServer
在同一目录中我用
启动 phpphp -S localhost:8000
不知道出了什么问题。虽然我相信我有 pdo,但我尝试用 phpbrew 安装它(以防万一),安装另一个 php 版本(7.0.7)。但是当我尝试使用
安装扩展时,我得到了库存phpbrew ext install pdo-mysql
其实我真的不知道自己在做什么。我在 php 文档中看到您必须像这样编译:
--with-pdo-mysql[=DIR]
我不知道这意味着什么......我很迷失,正如你所看到的。我认为这可能比我想象的要容易,但我不知道该怎么做,要改变什么。请帮忙!!!
最佳答案
我将在此处进行一些更改,而不是将 PDO 作为函数,而是创建一个名为“connection.php”的新页面并将其包含在您需要连接的任何页面上。例如:
<?php
try{
$pdo= new PDO("mysql:dbname=NAME; host=localhost; charset=utf8", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
?>
要包含页面:
include('connection.php');
或
require_once('connection.php');
改变
return $stmt->fetchAll( PDO::FETCH_OBJ);
到
$result[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
然后在 foreach 循环中迭代每个结果,具体取决于结果集之前有多少外部数组,您可能需要 1-2 个 foreach 循环。
例如:
foreach($result as subResult){
foreach($subresult as $rows){
echo $rows['actor_id'];
//or do a var_dump($rows);
}
}
关于php - 通过 php 使用 pdo 连接到 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37730931/