4

What I need is to have a list name => value to be able to make MySql queries. My problem is, I can access MySql records, but I also need to access table's column names, what should I change in my code?

Thanks

$query = "SELECT * FROM test_table";
$result = mysql_query($query) or die("Erro!: " . mysql_error());
if (mysql_num_rows($result) > 0) {
    $row = mysql_fetch_array($result);
    if(is_array($row)) {
        foreach ($row as $col => $val) {
            echo $col." = ".$val."<br>";
        }
    }
}

ok, so now why can't I join the values to then make my sql queries?

while($row = mysql_fetch_assoc($result)) {
        foreach ($row as $col => $val) {
            $colunas .= join(",",$col);
            $valores .= join(",",$val);
        }
        echo "colunas = ".$col."<br>";
        echo "valores = ".$val."<br>";
    }

I just get empty colunas and valores

Thanks, sorry if it seems to easy, but I'm lost

1
  • I think some books or manuals can be useful in beginning of studying. Maybe dev.mysql.com/doc Commented May 24, 2011 at 10:10

3 Answers 3

12

You needs while loop and a call to mysql_fetch_assoc

  while($row = mysql_fetch_assoc($result)) {   
        foreach ($row as $col => $val) {
            echo $col." = ".$val."<br>";
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

2

use mysql_fetch_assoc,

see : http://www.php.net/manual/en/function.mysql-fetch-assoc.php

Comments

2

I think you mixed up some variable names, and, you don't need the join function, since you're adding one column name at a time. does this work?

$colunas=$valores="";

while($row = mysql_fetch_assoc($result)) {
        foreach ($row as $col => $val) {
            $colunas .= $col.',';
            $valores .= $val.',';
        }
        echo "colunas = ".$colunas."<br>";
        echo "valores = ".$valores."<br>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.