PHP-Having issues echoing from mysql using GET

69 Views Asked by At

I am new at PHP, and I am trying to echo a particular field from my DB using the ID in my URL as reference. However instead of echoing the value it echo's back the ID.

What am doing wrong? Is there a better way of doing this? Thanks in advance.

I an trying to echo the datecreated field from ID that I have in my URL. The url is www.example.com/client_profile.php?id=1001

<div class="thumb-info mb-md">
    <img src="assets/images/!logged-user.jpg" class="rounded img-responsive" alt="John Doe">
    <div class="thumb-info-title">
        <?php
            echo $_GET['id'];  //Output: myquery
            $result = mysql_query("SELECT * FROM client WHERE id = '" . $_GET['id'] . "'");
            while($row = mysql_fetch_array($result)){
                echo "<span class='thumb-info-inner'>$row.['datecreated'].</span>";
            }
        ?>
    </div>
</div>

Updated Code

<?php
mysql_connect("localhost", "my user", "my pass") or
die("Could not connect: " . mysql_error());
mysql_select_db("my db");

$id = (int)$_GET['id'];  //Output: myquery
echo $id;
$result = mysql_query("SELECT * FROM client WHERE id = $id");
while($row = mysql_fetch_array($result)){
    echo "<span class='thumb-info-inner'>" . $row['datecreated'] . "</span>";
}?>

Which echo's both ID and the Value from DB

1

There are 1 best solutions below

6
On

Try this.

<div class="thumb-info mb-md"> <img src="assets/images/!logged-user.jpg" class="rounded img-responsive" alt="John Doe">
    <div class="thumb-info-title">
        <?php
            $id = (int)$_GET['id'];  //Output: myquery
          echo $id;
            $result = mysql_query("SELECT * FROM client WHERE id = $id");
            while($row = mysql_fetch_array($result)){
                echo "<span class='thumb-info-inner'>" . $row['datecreated'] . "</span>";
          }?>
    </div>
</div>

In your current code your concatenation was off for displaying the $row data. You also were open to SQL injections. To fix the SQL injections I cast your id as an int, here's a thread on that SQL Injection Protection - Cast from string to int. You also could use the mysql_real_string_escape (order of words might be off there). You should switch over to PDO and parameterized queries when you can though, How can I prevent SQL injection in PHP?.