我正在使用下面的代码将数据库转换为json
<?php
header('Content-type:application/json');
mysql_connect('localhost','root','')or die('cannot connect');
mysql_select_db('sanpham');
$sql = "SELECT * FROM cpu";
$result = mysql_query($sql);
if(!$result)
{
echo 'Lỗi SQL: '.mysql_error();
echo "\r\n<br />";
echo 'SQL: '.$sql;
exit;
}
$rows = array();
while($row=mysql_fetch_array($result)){
$rows[]=$row;
}
echo json_encode($rows);
?>
在我的php文件中没有错误,没有数据库,没有任何显示。请帮助我 。非常感谢
答案 0 :(得分:3)
不推荐使用:mysql_connect():不推荐使用mysql扩展程序,将来会删除它:在中使用mysqli或PDO
警告建议使用pdo或mysqli。
mysqli:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM cpu";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$rows = array();
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
echo json_encode($rows);
} else {
echo "no results found";
}
mysqli_close($conn);
?>
PDO:
<?php
$host = 'localhost';
$db = 'sanpham';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbh = new PDO($dsn, $user, $pass, $opt);
$sql = $dbh->query("SELECT * FROM cpu");
$rows = array();
while ($row = $sql->fetchall()) {
$rows[] = $row;
}
echo json_encode($rows);
?>
答案 1 :(得分:0)
你可以简单地在存储mysql数据库数据的数组上使用json_encode方法:
<?php
$host = "localhost";
$db = "psychocodes";
$user = "your username"; //enter your database username
$pass = "your password"; //enter your database password
$conn = new mysqli($host,$user,$pass,$db);
$rows = array();
$sql = "SELECT * FROM data";
$result = $conn->query($sql) or die("cannot write");
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
echo "<pre>";
print json_encode(array('serverres'=>$rows));
echo "</pre>";
?>
答案 2 :(得分:-1)
使用此
<?php
//open connection to mysql db
$connection = mysqli_connect("hostname","username","password","dbname") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from tablename";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
?>