How to individualize database queries with PHP?

Asked

Viewed 40 times

0

Hello, good morning. I have the following problem:

I want to handle SQL output using PHP, displaying the values individually and custom.

For example, I have a database with the values

Tomate | Cebola | Milho    
   2        4       1     

I would like to do something with PHP of this genre

<?php 
  $conn = mysqli_connect ("localhost", "usuario", "senha", "banco");
  $sql = "SELECT * FROM tabela";
  $query = mysqli_query ($conn, $sql);
  /*não sei como "transformaria" o resultado das consultas 
  em variaveis individuais*/
  echo "Você tem $x Tomate(s), $y Cebola(s) e $z Milho(s)";
?>

How can I do what I need???

1 answer

0


I would recommend you use something like PDO, since it seems to be using pure PHP, it would look something like this:

<?php

$servername = "localhost";
$username = "usuario";
$password = "senha";
$dbname = "banco";

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $stmt = $conn->prepare("SELECT * FROM tabela");
  $stmt->execute();

  $results = $stmt->fetchAll();
  foreach ($results as $result) {
    echo 'tomate: ' . $result['tomate'];
    echo 'cebola: ' . $result['cebola'];
    echo 'milho: ' . $result['milho'];
  }

} catch(PDOException $e) {
  echo "Error: " . $e->getMessage();
}
$conn = null;
?>

I recommend reading the documentation of PDO

  • 1

    Thank you, friend. I would also like to know if there is any way to do this using jQuery and ajax, to make things dynamic.

  • Yes, you play the data via ajax to a script php file that runs the query, to receive data would be the same idea, check out this post http://programmerblog.net/php-pdo-ajax-tutorial-example/

  • 1

    Thank you very much!!!!!!!!!!!

Browser other questions tagged

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