2018-07-22 05:33
浏览 18


lets say I have a single record with fields; id, username and password inside of a database. how do I use php to display the username from the first record field without using a while, for or if loop?

Can some write a script for me please?


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

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;


this is the config.php file

/* 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条回答 默认 最新

  • douao3636 2018-07-22 05:57

    Using PDO for prepared statements:

    $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();

    Then Run your SQL query:

    $stmt = $conn->prepare('SELECT username FROM yourTableName LIMIT 1');
    $username = $stmt->fetchAll();
    echo $username[0];
    //Or foreach($username as $name){echo $name;}

    That code should be wrapped inside php tags <?php //the code ?>

    UPDATE from comments it showed up that you are using MYSQLI, SO you should use something like:

    $mysqli = new mysqli("localhost", "username", "password", "DBname");
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s
    ", mysqli_connect_error());
    $query = "SELECT username from users ORDER by username DESC LIMIT 1";
    $result = mysqli_query($mysqli, $query);
    $result = mysqli_fetch_object($result);
    echo $result->username;
    解决 无用
    打赏 举报

相关推荐 更多相似问题