4

I am brand new to php/mysql, so please excuse my level of knowledge here, and feel free to direct me in a better direction, if what I am doing is out of date.

I am pulling in information from a database to fill in a landing page. The layout starts with an image on the left and a headline to the right. Here, I am using the query to retrieve a page headline text:

<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
    die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
    echo $row["banner_headline"];
}
?>

This works great, but now I want to duplicate that headline text inside the img alt tag. What is the best way to duplicate this queries information inside the alt tag? Is there any abbreviated code I can use for this, or is it better to just copy this code inside the alt tag and run it twice?

Thanks for any insight!

cagatayodabasi
  • 762
  • 11
  • 34
keithiopian
  • 123
  • 1
  • 2
  • 11
  • 4
    You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). – Quentin Mar 25 '13 at 14:48

2 Answers2

3

You are, as the comment says, using deprecated functions, but to answer your question, you should declare a variable to hold the value once your retrieve it from the database so that you can use it whenever your want.

<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
    die("Database query failed: " . mysql_error());
}

$bannerHeadline = "";

while ($row = mysql_fetch_array($result)) {
    $bannerHeadline = $row["banner_headline"];
}

echo $bannerHeadline; //use this wherever you want

?>
woz
  • 10,888
  • 3
  • 34
  • 64
  • Excellent, this is just what I was looking for, thank you for the insight. Though now that I see it is deprecated, I will start researching something more current. Thanks for your help! – keithiopian Mar 25 '13 at 15:02
2

It is hard to help without knowing more. You are pumping the results into an array, are you expecting to only return one result or many banner_headline results? If you will only ever get one result then all you need to do is something like this:

PHP:

$result = mysql_query("
    SELECT `banner_headline`
    FROM `low_engagement`
    WHERE `thread_segment` = 'a3'", $connection) or die(mysql_error());
// This will get the zero index, meaning first result only
$alt = mysql_result($result,0,"banner_headline");

HTML:

<html>
<body>
<!--- Rest of code -->
<img src="" alt="<?php echo $alt ?>">

On a side note, you should stop using mysql-* functions, they are deprecated.
You should look into PDO or mysqli

Jonathan Jones
  • 473
  • 4
  • 10