Skilledway
Skilledway

Reputation: 9

Querying UserID from database

I've been trying for ages to figure this out, but I can't do it.

$sqluser = "--";
$sqlpass = "--";
$hostname = "localhost"; 

$clientuser = $_COOKIE['user'];
//connection to the database
$dbhandle = mysql_connect($hostname, $sqluser, $sqlpass) 
 or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("clhtechn_si1",$dbhandle) 
  or die("Could not select database!");
//execute the SQL query
$idfinder = mysql_query("SELECT id FROM `si_customers` WHERE username='$clientuser'") or die(mysql_error());
$clientid = mysql_fetch_assoc($idfinder);
$query = "SELECT invoice_id, date, SUM(total) as invoiceTotal
          FROM si_invoices
          LEFT JOIN si_invoice_items ON si_invoices.id = si_invoice_items.invoice_id
          WHERE si_invoices.customer_id='$clientid'
          GROUP BY invoice_id
          ORDER BY invoice_id";
$result = mysql_query($query);

$row=0;
while ($record = mysql_fetch_assoc($result))
{
    $class = 'd' . ($row % 2);
    $inv_date=substr($record['date'], 0, -9);
    $inv_total=$record['invoiceTotal'];
    $invoice_total=number_format($inv_total, 2);

    echo "<tr class=\"{$class}\">";
    echo "<td valign='top'>{$inv_date}</td>";
    echo "<td valign='top'>{$record['invoice_id']}</td>";
    echo "<td valign='top'>$invoice_total</td>";
    echo "<td><a href='invoices/Invoice_{$record['invoice_id']}.pdf' target='_blank'>";
    echo "<img src='urlhere' width='17' height='17' alt='PDF File' border='0' /></a></td>";
    echo "</tr>";
    $row++;
}
//close the connection

mysql_close($dbhandle);

Here is how my customers table is aligned: Link to picture.

What is wrong with my code, and what code can I use to fix it? Help is appreciated.

Upvotes: 0

Views: 86

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157839

$clientid is an array as mysql_fetch_assoc() returns this type.

$row = mysql_fetch_assoc($idfinder);
$clientid = $row['id'];

also, you need to format $clientuser properly before placing it in a query.
So, the full code would be

$user = mysql_real_escape_string($_COOKIE['user']);
$sql = "SELECT id FROM `si_customers` WHERE username='$user'";
$res = mysql_query($sql) or trigger_error(mysql_error());
$row = mysql_fetch_assoc($res);
$clientid = $row['id'];

To make it the way you want, you have to use some abstraction library
With which you will have your id in one line (it's actually 2 lines just for sake of readability)

$sql = "SELECT id FROM si_customers WHERE username=?s";
$clientid = $db->getOne($sql,$_COOKIE['user']);

Here you can see an example of such a Mysql abstraction library.

Upvotes: 1

Related Questions