How to better optimize the Mysql connection and information listing script?

Asked

Viewed 94 times

-1

How to better optimize connection script and listing information from MySQL? Because I check in my researches several ways to do this, but I do not know if this is a correct practice both of connection to database and to list information from MySQL.

php connection.

<?php
$con = mysqli_connect("localhost", "root", "", "guaraparivirtual");
?>

index php.

<?php include ("conexao.php"); ?>

<?php

$seleciona=mysqli_query($con,"select * from noticias");
while($campo=mysqli_fetch_array($seleciona)){
?>

<?php echo $campo["Titulo"]."</br>"; ?>

<?php
}
?>
  • 1

    select id, titulo from noticias and prints a link with the code(id) of the news and the title, <a href=\"noticia/$campo["id"]\" target="_blank">$campo["titulo"]</a><br/>, unless your title contains no special characters. Note tag <br>.

  • 1

    Define passwords directly in the code, the way it is in the conexao.php is not ideal, there are other ways, I specifically talked about one of the other ways here. About query optimization @Leo Caracciolo’s reply mentions one of the improvements that can be made, which is to avoid using the *.

2 answers

2

Select only the columns that matter to save server resources and streamline your search, in your case the column titulo

More elegant and easy to read.

<?php 
   include ("conexao.php");
   $seleciona=mysqli_query($con,"select titulo from noticias");
     while($campo=mysqli_fetch_array($seleciona))
     {
       echo $campo["Titulo"]."</br>"; ?>
     }
?>

0

Instead of using SELECT * FROM, you can use SELECT titulo FROM noticias, there is no reason to take all fields, and only use the title and etc. This way the search will be faster. I also advise you to use PDO

<?php
try {
  $pdo = new PDO('mysql:host=localhost;dbname= guaraparivirtual', 'root', '');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}
?>


$sql = $pdo->prepare("SELECT titulo FROM noticias");
$ln = $sql->fetchObject();

echo $ln->titulo;

but regardless of what to use, whenever you are not going to use all the fields in the table, select only the ones you are going to use. ç

Browser other questions tagged

You are not signed in. Login or sign up in order to post.