I’m fairly novice with SQL (reading right now). I’m wondering if there is a better way in PHP to get a MySQL data item than the following:
$sql = "SELECT `topic_id` from `topics` WHERE `user_id` = ".$userId." AND `topic` = ".$topic.";";
$topicRow = mysql_query($sql);
$row = mysql_fetch_array($topicRow);
$topicId = $row['topic_id'];
I mean, 4 variables were created to get 1 item. Am I doing something incorrectly?
Thank you
The amount of vars is not a real issue, you could put the sql-string in your query if you want, but you’re not really winning anything measurable. Please do not look for efficiency there. While the answers of @genesis and @patapizza are correct as far as I can see, they do not help you in any way to better your code, but only make it less readable.
You should look into parametereized queries (take a look at using PDO): You should split your content (
$userId) and your SQL-command.An example from the manual:
You don’t have to escape the various things you put in your query, so you’re save from injection.
(ow, and coincidently, only using 2 variables.. jeeeej 🙂 )