I do not understand what's the point of your code: go through all the records to stay with only the last one.
If that is the intention the best thing would be to filter the query so that it brings you that single record you want.
The problem that arises about the scope of the variable of interest could be resolved with a function that returns the result.
For example, this query would bring you the last record, assuming you have a% incremental auto% column.
function getTitulo($urlID){
$title="";
$sql="SELECT title FROM draws WHERE urlID='$urlID' ORDER BY id DESC LIMIT 1";
$reg = mysql_query($sql);
/*Dado que es un solo registro, no hace falta el while*/
$data = mysql_fetch_array($reg);
$title = $data ['title'];
return $title;
}
If on the other hand you want all the records, then the correct thing would be to declare the variable outside the id
as an array, which you would then fill in the while
:
function getTitulo($urlID){
$arrTitles=array();
$sql="SELECT title FROM draws WHERE urlID='$urlID'";
$reg = mysql_query($sql);
while($data = mysql_fetch_array($reg)) {
$arrTitles = $data ['title'];
}
return $arrTitles;
}
To use both functions from anywhere you just have to worry that the while
function is in the scope where you want to use it. Then you call it, passing it the parameter and you store the value that the function returns or you use it directly.
$datosDeGetTitle=getTitle('elIdURL');
In getTitle()
you will have what the function returned.
NOTES:
- Depending on the scope and organization of your program, this could also be done through
$datosDeGetTitle
, creating instances of a
class which would have methods to return the different
elements.
- Querying your code is vulnerable to SQL injection attacks. To shield the code it will be necessary, if it is possible for you, to go from
the extension
clases
to mysql.*
or a mysqli
. The extension you use
now it has been declared obsolete and will stop working in PHP 7.