McDuck4
McDuck4

Reputation: 662

SELECT column mysql

I am in a little bit in doubt, if I am on the correct path here. I have a mysql database, where I have login details of users. I am making a profile page, where I would like the informations on a user is shown to the user. I am now trying to return the firstname there is a column in the database. Am I on the correct path with this code?

<td>
    Firstname
    <?php
      $stmt = $mysqli->prepare("SELECT firstname FROM login");

      $stmt->execute();

      $fname = null;

        $stmt->bind_result( $fname);

        while($stmt->fetch()) {
          $firstname = // Code here
          echo $firstname;
        }

      $stmt->close();
      $mysqli->close();
    ?>
  </td>

Update:

I tried to make the code a little bit smaller. This code actually retrives users, but it is all the users in the database, and not only the user I am logged into with. Should the SELECT query be asigned with the primarykey, if I only need the firstname on the current user I am logged in as?

<td>
    Firstname
    <?php
        $sql ="SELECT firstname FROM login;";
        $res = $mysqli->query($sql);
        //print($res);
        if($res){                                       
            while($row = $res->fetch_assoc()){
               echo $row['firstname'];

          }                               
        }
      ?>        
  </td>

Upvotes: 1

Views: 50

Answers (2)

Darth Egregious
Darth Egregious

Reputation: 20106

If you're playing around with PHP and trying to learn how things work, you're on a great path. If you're planning on deploying this code to the internet, you have a few issues:

  1. Your markup seems off. Why are you putting all of the first names in a single <td>?
  2. You shouldn't have a SQL query happening inside of a markup. What if you want to show results from a cache or a text file some day? Ideally you wouldn't even mix PHP and HTML. Some folks use PHP's built-in templating abilities, but it's generally preferred to use a template language like jade or twig.
  3. Your code alignment isn't consistent.

But if you're just seeing what PHP can do, good job. Keep trying stuff out. It's the best way to learn for most people. Others like reading a book, then trying stuff.

Upvotes: 1

Fabio
Fabio

Reputation: 23490

You are on the correct path but you need to assign your array to a variable so you can print adding your column name in the scope and remove the bind of $fname

//$stmt->bind_result($fname);
while($column = $stmt->fetch()) {
     $firstname = $column['firstname'];
     echo $firstname;
}

Or you can just use the variable you bind before

$stmt->bind_result($fname);
while($stmt->fetch()) {
     echo $fname;
}

You could optimize your query and limit tresult to only one user by adding a WHERE condition to your query, you can use user ID for example

SELECT firstname FROM login WHERE userid = 1

Upvotes: 2

Related Questions