Assign a database value to a php variable

Asked

Viewed 263 times

-2

the variable $query appears to be empty as it adds no value in the database.

Where am I going wrong?

$aVar = mysqli_connect('localhost');
$query = mysqli_query($aVar, "SELECT MAX(id_evento) FROM eventos2");

$sql->bindValue(':idp',$query);
  • The function mysqli_connect() should receive 4 parameters neh no? host, user, password and database.

2 answers

-2

If your intention is to retrieve the last record from the table, you can try it as follows:

<?
$host     = "localhost";
$user     = "root";
$password = "";
$database = "nome_do_banco_de_dados";
$dblink = mysqli_connect($host, $user, $password, $database);
if (mysqli_connect_errno()) {
    echo "Erro ao conectar com o banco de dados: ".mysqli_connect_error();
    exit();
}
$sqlquery = "SELECT MAX(id_evento) as codigo FROM eventos2";
if ($result = mysqli_query($dblink, $sqlquery)) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo $row["codigo"];
    }
    mysqli_free_result($result);
}
mysqli_close($dblink);
?>

-2

Good afternoon dear I have some suggestions.

First the instance of the connection is called as follows

<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");

if (!$link) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

ref:https://www.php.net/manual/en/function.mysqli-connect.php

Anyway it seems that Voce wants to use the result of a search as parameter for another sql command

$sql->bindValue(':idp',$query);

My recommendation is to use subquery that works on any DBMS, as in the case of sqlserver : https://docs.microsoft.com/pt-br/sql/relational-databases/performance/subqueries?view=sql-server-ver15

Example 1:

"INSERT INTO tabela1 (id,nome) VALUES ( (SELECT MAX(id) FROM tabela1) + 1, 'Nome')"

Example 2:

"UPDATE tabela1 
SET nome = (SELECT nomeCompleto FROM pessoa WHERE pessoa.id = tabela1.id_pessoa)"

Browser other questions tagged

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