虽然我有,但没有选择数据库

时间:2016-04-26 10:08:59

标签: php html mysql

从错误消息中显示无效查询:未选择数据库,即使我在 template.php中选择了数据库

这是我正在制作的代码。这是一个显示管理员用户的表格: anvandare.php :     

      $query = "select * from user";

      $run = mysql_query($query);
if (!$run){
  die('invalid query: ' . mysql_error());
}

while($row=mysql_fetch_array($run)){

      $email = $row['email'];
      $company = $row['company'];
      $fname = $row['fname'];
      $licensID = $row['licensID'];
      $tel = $row['tel'];

?>
        <td><?php echo $email; ?></td>
        <td><?php echo $company; ?></td>
        <td><?php echo $fname; ?></td>
        <td><?php echo $licensID; ?></td>
        <td><?php echo $tel; ?></td>
        <td> ta bort </td>
        </tr>
<?php } ?>
</table>
            </div> <!-- Stänger jumbotron --> 
          </div> <!-- Stänger jumbotronbekraftat --> 
        </div> <!-- Stänger container --> 
<?php        
  echo $navigation_admin;
  echo $header;
  ?>

这是databas.php

 <?php
 session_start();
   session_regenerate_id();
   $mysqli = new mysqli("localhost", "root", "", "Webbprojekt");
   mysqli_set_charset($mysqli,"utf-8");
?>

如何解决此问题?因为include (template.php)我已经连接了我的数据库。

4 个答案:

答案 0 :(得分:1)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully"; 
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

使用上面的代码建立数据库连接 更多信息

http://www.w3schools.com/php/php_mysql_connect.asp

答案 1 :(得分:0)

<?php
$host="localhost"; $db="dbname"; $charset="utf8"; $user="root"; $pass="";
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $pass, $opt);
?>

在您的模板中使用它以获得更高的安全性,但您可以将其用于您的项目:

<?php
mysql_connect("localhost","root","pass");
mysql_select_db("dbname");
?>

答案 2 :(得分:0)

您的PDO新代码应如下所示

$db_con = new PDO('mysql:host=localhost;dbname=db-name', 'username', 'password');
    $statement = $db_con->prepare("select * from user");
    $statement->execute();
    $result = $statement->fetchAll(PDO::FETCH_ASSOC);
   foreach($result as $row)
   {
     $email = $row['email'];
     $company = $row['company'];
    $fname = $row['fname'];
     $licensID = $row['licensID'];
     $tel = $row['tel'];
   }

答案 3 :(得分:0)

在您的database.php中,您使用mysqli_ ()创建了连接,但在.php中您使用了mysql_query($ query);而不是使用mysql _ 使用mysqli _ *

我的意思是说在整个项目中使用mysql_ ()或mysqli _ ()。因为mysql_ ()被折旧所以使用mysqli _ ()