gpt4 book ai didi

php - 从 mysql php 选择数据

转载 作者:行者123 更新时间:2023-11-29 18:29:57 24 4
gpt4 key购买 nike

我用它从 php 中的 mysql 中选择数据

<?php
error_reporting(E_ALL);
$servername = "localhost";
$username = "******";
$password = "******";
$database = "*******";

// Create connection
$conn2 = new mysqli($servername, $username, $password, $database);
$stmt = $conn2->prepare('SELECT id, title, views from `blog_main`');

$stmt->execute();
var_dump($stmt);

$result = $stmt->get_result();
while($r=$result->fetch_assoc())
{
echo "id: " . $r["id"]. " - Name: " . $r["title"]. " " . $r["views"]. "<br>";
}

$conn->close();
?>

但是没有显示结果,但如果我在 phpmyadmin 界面上运行此查询,它会返回行。这段代码在本地主机上运行良好,但是当我将其转移到 godaddy 的服务器时,我仅在准备好的语句中遇到这个问题。当我使用普通查询方法时,它显示行,只有准备好的语句不起作用。

这是 var dump 的值:

object(mysqli_stmt)#2 (10) { ["affected_rows"]=> int(-1) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(0) ["field_count"]=> int(3) ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["sqlstate"]=> string(5) "00000" ["id"]=> int(1) }

是否需要启用任何类型的扩展或者可能存在什么问题?

最佳答案

这是我对您问题的回答,

创建文件db.php

$dbInfo = array(
'host' => "localhost",
'user' => "******",
'pass' => "******",
'dbname' => "******"
);

创建dbcon.php

class database{
protected $databaseLink;
function __construct(){
include "db.php";
$this->database = $dbInfo['host'];
$this->mysql_user = $dbInfo['user'];
$this->mysql_pass = $dbInfo['pass'];
$this->databaseName = $dbInfo['dbname'];
$this->openConnection();
return $this->get_link();
}
function openConnection(){
$this->databaseLink = mysqli_connect($this->database, $this->mysql_user, $this->mysql_pass, $this->databaseName);
}

function get_link(){
return $this->databaseLink;
}
}

创建 func.php

include "dbcon.php";

function selectData(){
$db = new database();
$selectQuery = "SELECT id, title, views FROM blog_main";
$selectQuery = mysqli_query($db->get_link(), $selectQuery) or die(mysqli_error());
while($r = mysqli_fetch_assoc($selectQuery)) {
$rows[] = $r;
}
return $result = json_encode(($rows));
mysqli_close($db->get_link());
}

例如在index.php中,您可以从中获取SQL返回的数据

include "func.php";
$data = selectData();


$dataJson = json_decode($data, TRUE);

foreach ($dataJson as $key => $value) {
echo "id: " . $value['id']. " - Name: " . $value['title']. " " . $value['views']. "<br>";
}

祝你好运

关于php - 从 mysql php 选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45775136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com