Amateur here, just practicing some sql.
I am trying to assign php variables to my sql query results, and I thought I saw it work in this fashion, but it doesn’t seem to be working for me:
$query1 = mysql_query("SELECT * FROM markers WHERE id = '$markerid'"); $result = mysql_query($query1); $markerData = mysql_fetch_array($result, MYSQL_ASSOC); $name = $markerData['name']; $description = $markerData['description']; $directions = $markerData['directions']; $lat = $markerData['lat']; $lng = $markerData['lng']; $type = $markerData['type']; $addedby = $markerData['addedby'];
Is there some rule I am blatantly disregarding?
Additionally, I know sql is deprecated/unsafe, just trying to learn the basics here.
Sincere thanks for any help.
Advertisement
Answer
You should feed a query statement into the mysql_query function, not feed it with another mysql query:
$sql = "SELECT * FROM markers WHERE id = '$markerid'"; $result = mysql_query($sql);
Obligatory Note:
Please, don’t use
mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi – this article will help you decide which. If you choose PDO, here is a good tutorial.
It doesn’t matter if you’re still in the starting stage. Since you already know that API is deprecated and your queries are usafe, why not just start good habits.
This is by way of PDO with prepared statements:
$db = new PDO('mysql:host=localhost;dbname=DB_NAME', 'username', 'password'); $sql = 'SELECT * FROM markers WHERE id = :markerid'; $select = $db->prepare($sql); $select->bindParam(':markerid', $markerid, PDO::PARAM_INT); $select->execute(); $markerData = $select->fetch(PDO::FETCH_ASSOC); $name = $markerData['name']; $description = $markerData['description']; $directions = $markerData['directions']; $lat = $markerData['lat']; $lng = $markerData['lng']; $type = $markerData['type']; $addedby = $markerData['addedby'];