I am retrieving a lot of single data items from a mysql database and have constructed the code below whereby the variables for each data item is set to be identical to the ID that is queried. My problem is that the array contains some 50-100 elements and the query seems to be very slow as a result. I would very much appreciate if anyone can review the code and inform me if I can somehow optimize this such that it will execute faster. Thank you very much in advance.
$idArray = [ // contains some 50-100 elements in total
"BANANA",
"APPLE",
"COCONUT",
"PEAR",
];
foreach($idArray as $val) {
$query = "SELECT * FROM {$tableName} WHERE ID = '{$val}'";
$result = mysqli_query($conn, $query) or die('error');
while($data = mysqli_fetch_array($result)) {
$$val = $data["COINFO"];
}
}
Update: I have now tried to construct the query with the IN keyword instead but the query still seems to be executing very slowly on my server whereas there are no issues at all on my localhost. As such, I am wondering if there might be some other issue.
Based on the comment below, I understand that the most optimal approach is to apply parameterized queries and bind_param and I would very much appreciate if someone can translate the above code to the new updated approach!
mysqliyou should be using parameterized queries andbind_paramto add any data to your query. DO NOT use string interpolation or concatenation to accomplish this because you have created a severe SQL injection bug. NEVER put$_POST,$_GETor data of any kind directly into a query, it can be very harmful if someone seeks to exploit your mistake.mysqliis significantly less verbose, making code easier to read and audit, and is not easily confused with the obsoletemysql_queryinterface. Before you get too invested in the procedural style it’s worth switching over. Example:$db = new mysqli(…)and$db->prepare("…")The procedural interface is an artifact from the PHP 4 era whenmysqliAPI was introduced and ideally should not be used in new code.