我有一些PHP代码,我已经用一些信息创建了一个MySQL数据库。当我运行我的代码时,我得到了这个答案:"连接到MySQL",但该页面不会返回我的ID,名称和年份。任何人都能明白为什么会这样吗?
最诚挚的问候 MADS
<?php
//echo phpinfo();
$username = "root";
$password = "root";
$hostname = "127.0.0.1:8889";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT id, model, year FROM cars");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'model'}."Year: ".$row{'year'}."<br>"; //display the results
}
//close the connection
mysql_close($dbhandle);
?>
CREATE DATABASE `examples`;
USE `examples`;
CREATE TABLE `cars` (
`id` int UNIQUE NOT NULL,
`name` varchar(40),
`year` varchar(50),
PRIMARY KEY(id)
);
INSERT INTO cars VALUES(1,'Mercedes','2000');
INSERT INTO cars VALUES(2,'BMW','2004');
INSERT INTO cars VALUES(3,'Audi','2001');
INSERT INTO cars VALUES(4, 'Ferrari', '2013');
INSERT INTO cars VALUES(5, 'Lamborghini', '2012');
INSERT INTO cars VALUES(6, 'Mazda', '2010');
答案 0 :(得分:1)
您在以下行中使用了大括号而不是括号:
echo "ID:".$row{'id'}." Name:".$row{'model'}."Year: ".$row{'year'}."<br>"; //display the results
将其更改为:
echo "ID:".$row['id']." Name:".$row['model']."Year: ".$row['year']."<br>"; //display the results
答案 1 :(得分:0)
找到答案。我写的是模型而不是名字: - )
<?php
//echo phpinfo();
$username = "root";
$password = "root";
$hostname = "127.0.0.1:8889";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT id, name, year FROM cars");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'name'}."Year: ".$row{'year'}."<br>"; //display the results
}
//close the connection
mysql_close($dbhandle);
?>