Ricky T Ricky T - 3 months ago 8
MySQL Question

Compare values from two different tables, if equal then display

I have a variable called $row['mykey'] that was genterated from a query on table one, I have echoed
it to my page and it does display the value I'm looking for. Now I need to use this varible to set my new query
on table two, to only display results if it matches contractor_lock from table two. $stmt1 one works fine to display the entire table, but I want to use $stmt2 but get no data results. Thanks for any help!

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


$stmt1 = $conn->prepare("SELECT client_id, companyname, contact, contractor_lock FROM table_two");


$stmt2 = $conn->prepare("SELECT client_id, companyname, contact, contractor_lock FROM table two WHERE contractor_lock = $row['mykey']");

$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}

catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
}

Answer

You have to concatenate $row['mykey'] to stmt2 instead of including it directly because it might be interpreted as a string.

It should be like this

$stmt2 = $conn->prepare("SELECT client_id, companyname, contact, contractor_lock FROM table two WHERE contractor_lock = ?");
$stmt2->execute($row['mykey']);
Comments