0

关于以下代码,我有几个问题:

    // Create a new MySQL connection, inserting a host, username, passord, and database you connecting to
    $conn = new mysqli('xxx', 'xxx', 'xxx',);
    if(!$conn) {
        die('Connection Failed: ' . $conn->error());
    }

    // Create and execute a MySQL query
    $sql = "SELECT artist_name FROM artists"; 
    $result = $conn->query($sql);

    // Loop through the returned data and output it
    while($row = $result->fetch_assoc()) {
        printf(
            "Artist: %s<br />", $row['artist_name'], "<br />",
            "Profile: %s<br />", $row['artist_dob'], "<br />",
            "Date of Birth: %s<br />", $row['artist_profile'], "<br />",
            "Password: %s<br />", $row['artist_password'], "<br />"
        );
    }

    // Free memory associated with the query
    $result->close();

    // Close connection
    $conn->close();

如何分配artist_dob,artist_profileartist_password返回给浏览器?

声明$conn->error()是什么意思?我不明白这个->标志是做什么的。

4

3 回答 3

1

The printf() function will return the information to the screen. The $conn->error() will echo out a database error if there was one trying to connect. the -> means it's calling a function from an object so $conn is an object and it has lots of functions and $conn->query() means to run the query function on the $conn object.

You may want to look into beginner php object-oriented tutorials: https://www.google.com/search?q=beginner+guide+to+php+oop

于 2013-05-21T15:06:21.690 回答
1

这段代码全错了。它实际上必须是什么:

// Create a new PDO connection to MySQL
$dsn = "mysql:host=localhost;dbname=test;charset=utf8";
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$conn = new PDO($dsn,'root','', $opt);

// Create and execute a MySQL query
$sql = "SELECT artist_name FROM artists"; 
$stm = $conn->prepare($sql);
$stm->execute();
$data = $stm->fetchAll();

// Loop through the returned data and output it
?>
<? foreach($data as $row): ?>
        Artist: <?=$row['artist_name']?><br />
        Profile: <?=$row['artist_dob']?><br />
        Date of Birth: <?=$row['artist_profile']?><br />
        Password: <?=$row['artist_password']?><br />
<? endforeach ?>

它在许多(至少十几个)方面都更好。

于 2013-05-21T15:17:34.903 回答
0

The -> in PHP is used to call methods and public parametres from objects like the . in many other languages like C# or Java.

PHP: $object->method();

Java: object.method();

Also, your concatenate character is wrong. If you use the comma , you are passing multiple parametres to the function. To concatenate strings in PHP you have to use the point . like in other languages you would use the +.

PHP: "Some "."string" = "Some string"

Java: "Some "+"string" = "Some string"

Of course, you can concatenate strings in the function calling as an argument.

$string = "Print".$string;
printf($string);

is the same than

printf("Print ".$string);

于 2013-05-21T15:06:17.353 回答