Help with some errors and a question regarding showing database data in a form

I have a query
$query = mysql_query(“SELECT * from landlordsincome WHERE username = ‘admin’”);

this works fine BUT I want to replace the ‘admin’ with a variable $username which will hold the username of the currently signed in user and therefore pulls their data out of the db and nobody elses. BUT when I make the query

$query = mysql_query("SELECT * from landlordsincome WHERE username = $username");

I get the error that "Unknown column ‘admin’ in ‘where clause’ " ??? The value of $username is admin for the purposes of this test.

Anyone know whats happening and how to fix it?

Also can anyone point me in the right direction on how to then take the results from the query and show them in a form.

I thought something like to start with

$result = mysql_query($query);

But it generates this error
mysql_query() expects parameter 1 to be string, resource given

Once I have successfully given the results to a variable such as $result, this would be an array right? In this case the database only contains one row per user of 11 cols not including the username col. What is the command to get the column data out of that array? I have seen commands for getting rows of data out but not cols.

Once again thanks for the help.

mysql thinks admin is a column because you forgot the quotes around it that would make it a string value

:slight_smile:

Which is why during development you should code your queries in a way that gives you the error AND the query in case of an error, so you can see immediately what is wrong.


$query = "
  SELECT * 
  FROM landlordsincome 
  WHERE username = $username
";
$result = mysql_query($query) or die("mysql error " . mysql_error() . " in query $query");
while ($row = mysql_fetch_assoc($result)) {
    ... do whatever you want to do...
}

Please note that I left the error in your query :slight_smile:
And also note that mysql_query already gives you the query result set. You can then loop through it as in the code I posted. You can read more about it in the manual.

Another tip. If you have problems running a query, echo the query to the screen to see what will be run in mysql_query. You can usually see the error in the query pretty quickly then.


$query = 'select * from users';

echo $query;

die();

No, not right.

Say you run the above query.

$rs = mysql_query($query,$con);

$rs is a resource, not an array.

What is the command to get the column data out of that array?

mysql_fetch_assoc takes $rs as input and returns an associative array for each row of data in $rs one row at a time. The keys in the array will be the column names in the users table

while($row=mysql_fetch_assoc($rs)){
    echo $row['firstname']. ' '.$row['lastname'].'<br />';
}