PHP and MySQL Basics III -- Resulting Results

In the first two blogs entries on this series we set up a connection to MySQL and sent off a query. Now we need to get the data back from the database and into the application.

An Embarrassment of Riches

PHP has many options for what we want to do. But for the best place to start with was checking that rows were actually returned from a query. Below the results from a query are returned to a variable named $result. We can find out how many rows were returned from the server by examining $result->num_rows.
if (!$result = $mysqli->query($sql)) {

// Again, do not do this on a public site, but we'll show you how
// to get the error information
echo "Error: Our query failed to execute and here is why: \n";
echo "Query: " . $sql . "\n";
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}

// succeeded, but do we have a result?
if ($result->num_rows === 0) {
// Oh, no rows! Sometimes that's expected and okay, sometimes
// it is not. You decide.
echo "No data returned.";
exit;
}

This is a case where a programmer needs to know their data. In some cases you will not have a record or records returned because there is no data. Other times no data returned is a sign of big problems. So you have to have some education on what you expect back, and what you do not expect back.

Example

<?php
$mysqli = new mysqli("localhost", "root", "hidave", "world_x");

/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}

/* Select queries return a resultset */
$query="SELECT Name, CountryCode, District FROM city LIMIT 10";

if ($result = $mysqli->query($query)) {

if ($result->num_rows){
printf("Select returned %d rows.\n", $result->num_rows);

/* free result set */
$result->close();
} else {
echo "No data returned";
}
} else { // if ($result)
printf("Query failed: %s", $mysqli_error);
}

$mysqli->close();
?>

Sometime you just need the number of records, like number of outstanding customer orders. But in this case we are making sure we have some data to work with before proceedings.

So Now We Have Data

Now you have at least three choices -- rare, medium, or well done. Err, make that an associative array, an array or an object. Each have their uses and it is okay to have a favorite you use more.
$query="SELECT Name, CountryCode, District FROM city LIMIT 10";

if ($result = $mysqli->query($query)) {

if ($result->num_rows){
printf("Select returned %d rows.\n", $result->num_rows);
$assoc = $result->fetch_assoc();
$row = $result->fetch_row();
$obj = $result->fetch_object();

} else {
echo "No data returned";
}
} else { // if ($result)
printf("Query failed: %s", $mysqli_error);
}

So you make you choice of method and take the results. Here we use fetch_assoc(), fetch_row(), or fetch_object(). Depending on how you want to refer to the data, you use the one that fits the situation. Of course they are similar in use.

//associated array keys = column name, data = data from DB
printf("Sample assoc array %s -> %s\n", $assoc['Name'], $assoc['CountryCode']);

// simple row
printf("Sample row array %s -> %s\n", $row[0], $row[1]);

//object
printf("Sample object %s -> %s\n", $obj->Name, $obj->CountryCode);

Yes, you need to know all three as you will be looking at old code or someone else code that does not use your favorite. And sometimes you may need an object rather than a simple row.

Full Listing

<?php
$mysqli = new mysqli("localhost", "root", "hidave", "world_x");

/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}

/* Select queries return a resultset */
$query="SELECT Name, CountryCode, District FROM city LIMIT 10";

if ($result = $mysqli->query($query)) {

if ($result->num_rows){
printf("Select returned %d rows.\n", $result->num_rows);
$assoc = $result->fetch_assoc();
$row = $result->fetch_row();
$obj = $result->fetch_object();
} else {
echo "No data returned";
}
} else { // if ($result)
printf("Query failed: %s", $mysqli_error);
}
//associated array keys = column name, data = data from DB
printf("Sample assoc array %s -> %s\n", $assoc['Name'], $assoc['CountryCode']);

// simple row
printf("Sample row array %s -> %s\n", $row[0], $row[1]);

//object
printf("Sample object %s -> %s\n", $obj->Name, $obj->CountryCode);

$result->close();
$mysqli->close();
?>

Nhận xét

Bài đăng phổ biến từ blog này

Using MySQL to Output JSON

Pretty JSON with JSON_PRETTY()

Using find() with the MySQL Document Store

php


Save 50% on frames when you sign up for the GlassesShop.com newsletter!
Free Shipping At GlassesShop on orders $49+ ! No code required -
Weekly Deals starting at $6.95 plus an extra 20% off on orders $39+ At GlassesShop.com!
BUY ONE GET ONE FREE– use coupon code GSBOGO At GlassesShop.com - Ends 12/31/18
First Pair Free! Use Coupon Code FIRSTFREE At GlassesShop.com – Expires 12/31/2018
New Year, New Savings! Buy one Get one FREE! Use Code GSBOGO Details At GlassesShop.com
Best Buy Co, Inc.
Best Buy Co, Inc.
Best Buy Co, Inc.
button
banner
American National Standards Institute Inc.
SM_125x125button
SM_468x60banner
Iolo technologies, LLC
US/EU Warehouse Super Deal + Extra 10% OFF Code(GOFUN)
Up to 40% OFF + Extra 10% OFF Indoor & Patio Furniture(Code: fubuying)
Thousands of Car Accessories@TOMTOP.com
Thousands of Car Accessories@TOMTOP.com





























Seleção especial para os fãs de Harry Potter! Livros e artigos diversos inspirados na história de Harry, Hermione, Rony e cia!
Cupom exclusivo para os livros da série Harry Potter - CUPOM = POMODEOURO
Dia das crianças Submarino, até 10% off em brinquedos - CUPOM = VEMPROPLAY
10% off em telefonia - CUPOM = ALO10
Home
submarino.com.br
submarino.com.br
Planeta Criança - Diversos produtos com desconto para o Dia das Crianças
Zizo
banner
button
Lançamento FIFA 18 Edição Standard Microsoft Store Brazil
Lançamento FIFA 18 Edição Standard Microsoft Store Brazil




Contentmart
Hire - 468 x 60banner
Article in $3 - 125x125button
Os produtos mais vendidos na Multiar!
Home

Multiar
Home





Mochilas para Notebook Samsonite com Frete Grátis Sul e Sudeste
Conversor e gravador digital com Frete Grátis Brasil (exceto Norte)
Mouses HP com Frete Grátis Sul e Sudeste
WalmartBR
WalmartBR
WalmartBR
WalmartBR
HOMEPAGE
NOTEBOOKS
ALL IN ONE
IMPRESSORAS E SCANNERS
CARTUCHOS E TONERS
ACESSÓRIOS



Nossa melhor proteção para PC, Mac ou dispositivos móveis De R$ 109,00 por R$ 69,00
Nossa melhor proteção para todas as suas formas de se conectar De R$ 169,00 por R$ 99,00
Nossa melhor proteção, mais backup de PC e recursos de segurança da família para você e as pessoas importantes na sua vida De R$ 249,00 por R$ 139,00
Symantec Brazil
Symantec Brazil
Os produtos mais vendidos no ShopFácil!
HOME ShopFacil


eGlobal Central
GenericPro_1.jpgbanner
Relógios -5% de desconto no - CUPOM = FDA5-FBA4-582B-19D3




Informática