0

In the below script I want to fetch data from mysql using a explode function and also a variable within an explode function. Here's how I want to get

<?php
include ('config.php');
$track = "1,2,3";
$i = 1
$trackcount = explode(",",$track);
$sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";
$retval = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['track_name']}";
}
mysql_free_result($retval);
?>

This is the code

$sql = "SELECT * FROM tracks WHERE id='$trackcount[$i]'";

I want sql to fetch data from tracks table where id = $trackcount[$i] Whatever the value of $trackcount[$i] mysql should fetch but it shows a blank screen. If I put this

$sql = "SELECT * FROM tracks WHERE id='$trackcount[1]'";

It works perfectly

2 Answers 2

1

save your $trackcount[$i] in one variable and then pass it in the query as given below

<?php
include ('config.php');
$track = "1,2,3";
$i = 1;
$trackcount = explode(",",$track);
$id=$trackcount[$i];
$sql = "SELECT * FROM tracks WHERE id='$id'";
$retval = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['track_name']}";
}
mysql_free_result($retval);
?>

and one more thing check your previous code with echo of your query and see what is passing ok.

echo $sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";//like this

problem is with your query

$sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";//change 

to

$sql = "SELECT * FROM tracks WHERE id='$trackcount[$i]'";
Sign up to request clarification or add additional context in comments.

Comments

0

Generally you would want to use the IN operator with this type of query, so for you this would be:-

$sql="SELECT * FROM `tracks` WHERE `id` in (".$track.");";

or, if the $ids are in an array,

$sql="SELECT * FROM `tracks` WHERE `id` in (".implode( ',', $array ) .");";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.