Reputation: 129
There are a couple questions I have regarding the following code:
// 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();
How can I assign artist_dob
, artist_profile
, and artist_password
and return it to the browser?
What does the statement $conn->error()
mean? I don't understand what the ->
sign does.
Upvotes: 0
Views: 1613
Reputation: 485
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);
Upvotes: 0
Reputation: 157828
This code is all wrong. What it actually have to be:
// 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 ?>
And it is in many (at least a dozen) ways better.
Upvotes: 1
Reputation: 12031
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
Upvotes: 1