Jump to content

MYSQL QUERY CANNOT RECOGNIZE THE ID IN VARIABLE FORM


phpnewbie007
Go to solution Solved by Ch0cu3r,

Recommended Posts

Hi Members,

 

I am search for the reason for the problem why my mysql query cannot fetch data and store in file based on id in $variable form. For example, $sql="SELECT * FROM mytable WHERE mine_id='1234'"; works for me. But when i use $sql="SELECT * FROM mytable WHERE mine_id='$id'";, files are created as empty. I chanaged the quotes and could not store the data in file. So anyone please help me.

For more clear, i attach the part of my code

for ($i=0;$i<=10;$i++)
    {

$id=$seqs[$i];
$dbo = new PDO($dbc, $user, $pass);
echo $sql = "SELECT * FROM mine_id WHERE locus_id='$id'";

$qry = $dbo->prepare($sql);
$qry->execute();
$data = fopen('file.csv', 'w');

   while ($row = $qry->fetch(PDO::FETCH_ASSOC))
              {
          fputcsv($data, $row);
             }
    }

Edited by phpnewbie007
Link to comment
Share on other sites

  • Solution

You have solved your issue but there is a problem with your code.

 

The database connection code should be outside of the for loop.

You are using prepared queries incorrectly. Values to be used in the query should be bound to placeholders.

The code for opening the file csv should also be outside of the loop too.

 

Your code should be like

// open csv file
$data = fopen('file.csv', 'w');

// cpnnection to database
$dbo = new PDO($dbc, $user, $pass);

// initiate prepared query. The ? is the placeholder for the id.
$sql = "SELECT * FROM mine_id WHERE locus_id= ? ";
$qry = $dbo->prepare($sql);

for ($i=0;$i<=10; $i++)
{
	$id = trim($seqs[$i]);

	// bind $id to placeholder in prepared query
	$qry->execute(array($id));

	// fetch result. While loop is only needed if more then one result is returned from the query.
	$row = $qry->fetch(PDO::FETCH_ASSOC);

	// write data to csv
    fputcsv($data, $row);
}

// close csv file
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.