简体   繁体   English

PHP 尝试连接到数据库

[英]PHP trying to connect to a database

I'm trying to connect to a database using php but i am getting 500 server error.我正在尝试使用 php 连接到数据库,但出现 500 服务器错误。

<?php
session_start();
$db = new mysqli("localhost", "username", "password", "db_name") or 
die("ERROR!!!");
$sql = "SELECT forum_id, forum_name FROM forum_tabl";
if($query = $db->prepare(sql)){
   $query = bind_result($f_id, $f_name);
   $query->execute();
}else{
  echo $db;
}
?>

You have to execute the query first before you use the bind_result()在使用 bind_result() 之前,您必须先执行查询

<?php
session_start();
$db = new mysqli("localhost", "username", "password", "db_name") or
die("ERROR!!!");
$sql = "SELECT forum_id, forum_name FROM forum_tabl";
if($query = $db->prepare(sql)){
  $query->execute();
  $query = bind_result($f_id, $f_name);
}else{
  echo $db;
}
?>

A few things you should check / try-您应该检查/尝试的几件事-

1) Your server is up and running (apache or whatever server you are using) 1) 您的服务器已启动并正在运行(apache 或您正在使用的任何服务器)

2) Remote mysql has premission for the IP of the device that is trying to connect to the database 2) 远程 mysql 对尝试连接数据库的设备的 IP 有权限

3) Add a "WHERE" clause to $sql = "SELECT forum_id, forum_name FROM forum_tabl"; 3) 在$sql = "SELECT forum_id, forum_name FROM forum_tabl";添加“WHERE”子句$sql = "SELECT forum_id, forum_name FROM forum_tabl";

eg : $sql = "SELECT forum_id, forum_name FROM forum_tabl WHERE something=?";例如: $sql = "SELECT forum_id, forum_name FROM forum_tabl WHERE something=?";

4) Check your variables - for instance in this line - 4)检查你的变量 - 例如在这一行 -

$sql = "SELECT forum_id, forum_name FROM forum_tabl";

forum_tabl might be forum_table forum_tabl可能是forum_table

Other then that , here is a bit cleaner code for your purpose.除此之外,这里有一些更简洁的代码供您使用。 Hope it works.希望它有效。

This is a config.php file which you can include to your other php pages that you need the use of the database:这是一个config.php文件,您可以将其包含到您需要使用数据库的其他 php 页面中:

<?php
    define('DB_SERVER', 'localhost');
    define('DB_USERNAME', 'your_username');
    define('DB_PASSWORD', 'your_password');
    define('DB_DATABASE', 'your_db');
    $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

Eventually , all other .php :最终,所有其他.php

<?php
    include("config.php");
    $stmt = $db->prepare("SELECT forum_id, forum_name FROM forum_tabl WHERE something=?");
    $stmt->bind_param("s", $something);
    $stmt->execute();
    $result = $stmt->get_result();
    if($result->num_rows === 0) exit('No rows');
    while($row = $result->fetch_assoc()) 
    {
        $forum_id = row['forum_id'];
        .......
    }
?>

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM