How to put two $Row results into variable?

Asked

Viewed 771 times

1

The code below gives error, it does not add the results of $row, only the comma and the dot. What to do?

Code that doesn’t work

  mysql_select_db('cadastro',$conexao);

$sql="select * from usuario";
$resultado = mysql_query($sql) or die ("Erro: " . mysql_error());

   // Obtém o resultado de uma linha como um objeto
while($row = mysql_fetch_array($resultado))
$variavel=($row['email'].",".$row['senha']."^") ;
// quero que tudo isso que esta entre () vire uma $variavel    
echo $variavel
?>

Code that feels right

<?php
@$conexao = mysql_connect('localhost','root','');

  mysql_select_db('cadastro',$conexao);

$sql="select * from usuario";
$resultado = mysql_query($sql) or die ("Erro: " . mysql_error());

   // Obtém o resultado de uma linha como um objeto
  while($row = mysql_fetch_array($resultado))
  echo $row['email'].",".$row['senha']."";    
  echo "^";
  ?>

That’s the code, so the result that it appears to me is EXAMPLE: [email protected],123456,^

email and password are in my database what I want is that all this echo, this result turn a variable

  • Check that the field names (email and password) are correct.

  • 1

    making echo $row['email']; and echo $row['senha']; values are printed correctly?

  • Yes appear EXAMPLE: [email protected],123456, Ai I need this result to turn into a variable

  • do you just want to print this variable? do you want it to become an array?

  • I want you to concatenate the email and password in a variable for example [email protected],123456,^

3 answers

1

Well, judging by the description, you’re pretty new.
The first thing you should always do when you are developing is enable errors (only disable them when the application is on production server, for example).
It seems to me that you fall in one of these situations:

Fields with empty values

$row['email'] and/or $row['password'] are empty strings;

Array indices or fields in the table do not exist

password and/or email are non-existent indexes, however you get no error as the directive display_errors in his php.ini is set to Off/0, disabling errors, so;

If this is the case, it justifies the fact of the value of $variavel always be ",^".


Steps that will help identify why this behavior:

Start by inserting this portion of code immediately at the beginning of the script:

<?php 

error_reporting(E_ALL);
ini_set('display_errors', 'On');

The above excerpt will cause any error to be displayed.
Then also remove the @ of the variable $conexão. Since that operator (@) will delete the error message of the current expression (if any). It would only justify its existence there if there was soon after the call of the function a or die('ERROR!'); or or exit('ERROR!'); as part of the whole expression. But of course, here it is almost certain (not to say 100%) that there is no error with the connection because if it were the case the expression mysql_query($sql) or die ("Erro: " . mysql_error()); would have printed the error regardless of how your error control directives are.

  • I think it would be nice to explain why the removal of @. Maybe indicate the function isset()?

0


Hi, I don’t have much time, so I’ll be brief. Your mistake is in looping, whereas you declared the beginning, but did not establish an end, or, the lines affected by that looping, see:

// Obtém o resultado de uma linha como um objeto
while($row = mysql_fetch_array($resultado))
$variavel=($row['email'].",".$row['senha']."^") ;
// quero que tudo isso que esta entre () vire uma $variavel    
echo $variavel

Normally, delimiters are placed to indicate the incision and the end of the expression that is part of the given group determined by the expression of the beginning of the other various types of control structures. But for the while we have: {} or : and endwhile;.

Below 2 examples, using the 2 types of delimiters [signs to group] above described.

1º {Chavetas}

// Obtém o resultado de uma linha como um objeto
$variavel = "";
while($row = mysql_fetch_array($resultado)){

$variavel .= $row['email'] . "," . $row['senha'] . "^";

}
echo $variavel;

Note that in this example, I first entered the variable $variavel outside the looping, and only then did I realize the values captured within the while using the operator .=

2º Using the : and endwhile;

// Obtém o resultado de uma linha como um objeto
$variavel = "";
while($row = mysql_fetch_array($resultado)):

$variavel .= $row['email'] . "," . $row['senha'] . "^";

endwhile;
echo $variavel;

Another observation is in relation to @ at the beginning of the connection expression, which should be kept under observation, taking into account that it suppresses errors returned in that expression, and also in relation to the mysql. I leave below some good sources.

Why do they say using @arroba to suppress errors is a bad practice?

What is the function of@at the beginning of PHP expressions

Error Control Operators - PHP.net

Why should we not use mysql type functions_*?

If I could have explained it better.

  • It worked out guy vlw...was that right there put between keys as Voce described above and it worked

-4

<?php
    //Incluir a conexão com banco de dados
    include_once('conexao.php');

    //Recuperar o valor da palavra
    $cursos = $_POST['palavra'];

    //Pesquisar no banco de dados nome do curso referente a palavra digitada pelo usuário
    $cursos = "SELECT * FROM cursos WHERE nome LIKE '%$cursos%'";
    $sub_menu_cursos = mysqli_query($conn, $cursos);

    if(mysqli_num_rows($sub_menu_cursos) <= 0){
        echo "Nenhum curso encontrado...";
    }else{
        while($rows = mysqli_fetch_assoc($sub_menu_cursos)){
            echo "<li>".$rows['nome']."</li>";
        }
    }
?>

Browser other questions tagged

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