如何使用php仅显示一个sql字段?

时间:2018-07-22 05:33:38

标签: php sql

让我说我有一条带有字段的记录;数据库内部的ID,用户名和密码。如何使用php从第一个记录字段显示用户名,而无需使用while,for或if循环?

有人可以帮我写个脚本吗?

<?php
session_start();

require_once 'config.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
<?php
$name = $_SESSION["name"];
$email = $_SESSION["email"];
?>
<?php

echo "your name is " . $name. "<br>";
echo "your email address is " . $email. "<br>";

$sql = "SELECT username FROM users LIMIT 1";
$result = mysqli_fetch_object($sql);
echo = $result->username;
?>


</body>
</html>

这是config.php文件

<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_NAME', 'users');

/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>

1 个答案:

答案 0 :(得分:0)

对准备好的语句使用PDO:

$servername = "localhost";
$username = "Database Username";
$password = "Database Password";
$dbname = "Database Name";
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    
}catch(PDOException $e)
{
    echo "Error: " . $e->getMessage();
}

然后运行您的SQL查询:

$stmt = $conn->prepare('SELECT username FROM yourTableName LIMIT 1');
$stmt->execute();
$username = $stmt->fetchAll();

echo $username[0];
//Or foreach($username as $name){echo $name;}

该代码应包装在php标签<?php //the code ?>

更新后的注释表明您正在使用MYSQLI,因此您应该使用类似以下内容的

$mysqli = new mysqli("localhost", "username", "password", "DBname");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT username from users ORDER by username DESC LIMIT 1";
$result = mysqli_query($mysqli, $query);
$result = mysqli_fetch_object($result);

echo $result->username;