0
The functions mysql_*
are obsolete and have been removed in PHP 7, butmysqli_* is similar, I’ll show you an example with mysqli...
//inicia uma conexão com o banco, note que aqui ja é selecionado o banco de dados
$con = new mysqli("server", "user", "pass", "db_name");
//Caso algum erro ocorra mostra o erro
if(mysqli_connect_errno()) trigger_error(mysqli_connect_error());
//Prepara o SQL
$stmt = $con->prepare("SELECT * FROM site");
//Executa o SQL
$stmt->execute();
//Obtem o resultado do SQL
$res = $stmt->get_result();
To show SQL has several forms...
fetch_all
- Stores the result in an array in another array:
$array = $res->fetch_all();
echo $array[x][y];
x
- consultation line
y
- consultation column
For example, $array[0][2]
returns the id (column at position 2) of the first row of the query (row at position 0), remembering whenever the array starts at position 0, that is, position 0 = 1°, position 1 = 2°, ...
fetch_row
- Stores a line in an array, usually a loop is used to catch all lines:
while($array = $res->fetch_row()) {
echo "$array[0], $array[1], $array[2]<br>";
}
Shows all names, adscode and id, the <br>
is just for better viewing
fetch_assoc
- It works the same way as fetch_row
, but instead of taking the position of the array, it is picked up by the name called by the database:
while($array = $res->fetch_row()) {
echo $array["titulo"]." (".$array["id"].") - ".$array["adscode"]."<br>"
}
In the fetch_assoc
it is not necessary to use in the order of the database columns, but not to use interpolation (variable in the middle of the string, "texto $variavel mais texto"
), error cause
fetch_array
- Saves data in an array, can be used both $array["coluna"]
as $array[x]
:
while($array = $res->fetch_array()) {
echo $array["titulo"]." (".$array["id"].") - $array[2]<br>";
}
In the fetch_array
can be used interpolation on numbers
fetch_object
- Returns an object with the data:
while($array = $res->fetch_object()) {
echo "$array->titulo ($array->id) - $array->adscode<br>";
}
In the fetch_object
it is possible to use interpolation quietly
How is your connection class with the bank? You use
mysql_*
(obsolete),mysqli_*
orPDO
– Costamilam
mysql_* (obsolete). I am using PHP 5.2
– HellFive Osborn