4

!!Please scroll down to "Edit 4"!!

This is driving me absolutely nuts!!

I have the following piece of code, and it doesn't work:

$importsectie = join("','",$importsectie);

$query1 = "SELECT * FROM smoelenboek WHERE sectie1 IN ('$importsectie') OR sectie2 IN ('$importsectie') OR sectie3 IN ('$importsectie') OR sectie4 IN ('$importsectie') OR sectie5 IN ('$importsectie') AND actief='ja' ORDER BY achternaam ASC";

$result1 = mysql_query($query1) or die(mysql_error());
while($row1 = mysql_fetch_array($result1)){

here the stuff I want to do with the results

}

When I echo $importsectie;, I get Tekenen','Wiskunde which is fine.

When I echo $query1;, I get SELECT * FROM smoelenboek WHERE sectie1 IN ('Tekenen','Wiskunde') OR sectie2 IN ('Tekenen','Wiskunde') OR sectie3 IN ('Tekenen','Wiskunde') OR sectie4 IN ('Tekenen','Wiskunde') OR sectie5 IN ('Tekenen','Wiskunde') AND actief='ja' ORDER BY achternaam ASC which I tried in PhpMyAdmin, it gave me the records I wanted, so this is fine as well.

I suspected it had something to do with $importsectie so I tried it without:

$importsectie = join("','",$importsectie);

$query1 = "SELECT * FROM smoelenboek WHERE sectie1 IN ('$importsectie') OR sectie2 IN ('$importsectie') OR sectie3 IN ('$importsectie') OR sectie4 IN ('$importsectie') OR sectie5 IN ('$importsectie') AND actief='ja' ORDER BY achternaam ASC";

$query2 = "SELECT * FROM smoelenboek WHERE sectie1 IN ('Tekenen','Wiskunde') OR sectie2 IN ('Tekenen','Wiskunde') OR sectie3 IN ('Tekenen','Wiskunde') OR sectie4 IN ('Tekenen','Wiskunde') OR sectie5 IN ('Tekenen','Wiskunde') AND actief='ja' ORDER BY achternaam ASC";

$result1 = mysql_query($query2) or die(mysql_error());
while($row1 = mysql_fetch_array($result1)){

here the stuff I want to do with the results

}

echo $query1; and echo $query2; give exactly the same result now (same result as above), but still the script doesn't work.

Now here is the weird thing: when I accidentally put some slashes before $importsectie, it suddenly worked!!

//$importsectie = join("','",$importsectie);

$query1 = "SELECT * FROM smoelenboek WHERE sectie1 IN ('$importsectie') OR sectie2 IN ('$importsectie') OR sectie3 IN ('$importsectie') OR sectie4 IN ('$importsectie') OR sectie5 IN ('$importsectie') AND actief='ja' ORDER BY achternaam ASC";

$query2 = "SELECT * FROM smoelenboek WHERE sectie1 IN ('Tekenen','Wiskunde') OR sectie2 IN ('Tekenen','Wiskunde') OR sectie3 IN ('Tekenen','Wiskunde') OR sectie4 IN ('Tekenen','Wiskunde') OR sectie5 IN ('Tekenen','Wiskunde') AND actief='ja' ORDER BY achternaam ASC";

$result1 = mysql_query($query2) or die(mysql_error());
while($row1 = mysql_fetch_array($result1)){

here the stuff I want to do with the results

}

Why?!? I really want to use the information in $importsectie. The stuff I want to do with it is make a pdf file with FPDF. $importsectie isn't used anywhere else in the code.

Edit

I tried it in a different way:

 $importsectie = $importsectie[0];

 $query1 = "SELECT * FROM smoelenboek WHERE sectie1='$importsectie' OR sectie2='$importsectie' OR sectie3='$importsectie' OR sectie4='$importsectie' OR sectie5='$importsectie' AND actief='ja' ORDER BY achternaam ASC";

 $query2 = "SELECT * FROM smoelenboek WHERE sectie1='Tekenen' OR sectie2='Tekenen' OR sectie3='Tekenen' OR sectie4='Tekenen' OR sectie5='Tekenen' AND actief='ja' ORDER BY achternaam ASC";

 $result1 = mysql_query($query1) or die(mysql_error());
 while($row1 = mysql_fetch_array($result1)){

 here the stuff I want to do with the results

 }

Both echo $query1; and echo $query2; give the same results again. Now using $query2 works fine (so no slahes before $importsectie). Using $query1 will start loading the pdf, the loading picture fills up and then it says "The PDF-file could not be loaded".

Edit 2

 $aantalsecties = count($importsectie);
 for($i=0;$i<=$aantalsecties-1;$i++){

     $importsectiedeel = $importsectie[$i];

     $query1 = "SELECT * FROM smoelenboek WHERE sectie1='$importsectiedeel' OR sectie2='$importsectiedeel' OR sectie3='$importsectiedeel' OR sectie4='$importsectiedeel' OR sectie5='$importsectiedeel' AND actief='ja' ORDER BY achternaam ASC";

     $query2 = "SELECT * FROM bonasmoelenboek WHERE sectie1='Tekenen' OR sectie2='Tekenen' OR sectie3='Tekenen' OR sectie4='Tekenen' OR sectie5='Tekenen' AND actief='ja' ORDER BY achternaam ASC";

     $result1 = mysql_query($query1) or die(mysql_error());
     while($row1 = mysql_fetch_array($result1)){

         here the stuff I want to do with the results

     }
 }

Both echo $query1; and echo $query2; give the same results as before again. Now both of them will start loading the pdf, but the loading picture doesn't fill up, the page keeps "Loading...". I have experienced the same problem when $query1 was built inside an if-statement.

Edit 3

So I switched to mysqli combined with prepared statements as suggested several times. Since I still have the same problem, I will now post the whole code.

First I have a page with checkboxes:

<form action="pdfrender.php" method="POST">
    <input type="checkbox" name="sectie[]" value="Tekenen">Tekenen<br>
    <input type="checkbox" name="sectie[]" value="Wiskunde">Wiskunde<br>
    <input type="submit" value="Sectiesmoelenboek">
</form>

The pdfrender.php is the following:

<?php

//Informatie binnenhalen
$importsectie = $_POST['sectie']; 

//Starten met het PDF-maak-script
require('../fpdf/fpdf.php');
class PDF extends FPDF
{
    //Koptekst
    function Header()
    {
        // Logo en een stukje leeg daaronder
        $this->Image('burggravenlaanheader.jpg',0,0,210);
        $this->Ln(20);
    }

    //Voettekst
    function Footer()
    {
        //1.5 cm boven de paginarand
        $this->SetY(-15);
        $this->SetFont('Arial','I',8);
        //Een hokje van paginabreed, 1 cm hoog, daarin pagina/totaal, geen rand, centreren
        $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
    }

}


//PDF aanmaken, pagina's laten tellen, nieuwe pagina beginnen
$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();


//Teller nodig om foto's links en rechts op de pagina te plaatsen
$teller = 1;


//This is going to be dynamic later, with a for-loop scrolling through the parts of the array
$importsectiedeel = $importsectie[1];


//Informatie uit database halen
include '../dbconi.inc';


//Prepare en bind
$query1 ="SELECT * FROM smoelenboek WHERE sectie1=? OR sectie2=? OR sectie3=? OR sectie4=? OR sectie5=? AND actief='ja' ORDER BY achternaam ASC";
$stmt = $con->stmt_init();
if(!$stmt->prepare($query1)){

    print "Failed to prepare statement\n";

}else{

    $stmt->bind_param("sssss",$importsectiedeel,$importsectiedeel,$importsectiedeel,$importsectiedeel,$importsectiedeel);
    $stmt->execute();
    $result1 = $stmt->get_result();
    while ($row1 = $result1->fetch_assoc()) {

        //Alle parameters klaarmaken voor printen
        $afkorting = $row1['afkorting'];
        $voorletters = $row1['voorletters'];  
        $voornaam = $row1['voornaam'];
        $tussenvoegsel = $row1['tussenvoegsel'];
        $achternaam = $row1['achternaam'];
        $sectie1 = $row1['sectie1'];
        $sectie2 = $row1['sectie2'];
        $sectie3 = $row1['sectie3'];
        $sectie4 = $row1['sectie4'];
        $taak1 = $row1['taak1'];
        $taak1 = str_replace("?","",$taak1);
        $taak2 = $row1['taak2'];
        $taak2 = str_replace("?","",$taak2);
        $taak3 = $row1['taak3'];
        $taak3 = str_replace("?","",$taak3);
        $taak4 = $row1['taak4'];
        $taak4 = str_replace("?","",$taak4);
        $taak5 = $row1['taak5'];
        $taak5 = str_replace("?","",$taak5);

         //Alle secties en taken onder elkaar zetten
        $onderelkaar = $sectie1."\n".$sectie2."\n".$sectie3."\n".$sectie4."\n".$taak1."\n".$taak2."\n".$taak3."\n".$taak4."\n".$taak5;

        //Zorgen dat minder dan 4 secties en minder dan 5 taken geen extra witregels oplevert
        $onderelkaar = str_replace("\n\n","\n",$onderelkaar);
        $onderelkaar = str_replace("\n\n","\n",$onderelkaar);
        $onderelkaar = str_replace("\n\n","\n",$onderelkaar);
        $onderelkaar = str_replace("\n\n","\n",$onderelkaar);

        //Fotolink klaarzetten indien aanwezig, anders geenfoto.jpg klaarzetten
        if (file_exists('fotos/'.$afkorting.'.jpg')){

            $foto = 'fotos/'.$afkorting.'.jpg';

        }else{

            $foto = 'fotos/geenfoto.jpg';

        }

        //Afkorting hoofdletters voor het afdrukken (was klein voor het aanroepen van de jpg)
        $afkorting = strtoupper($afkorting);

        //Naam en afkorting koppelen
        $titel = $voorletters.' ('.$voornaam.') '.$tussenvoegsel.' '.$achternaam.' ('.$afkorting.')';

        //Extra spaties verwijderen bij mensen zonder tussenvoegsel
        $titel = str_replace("  "," ",$titel);

        //Als de teller oneven is, persoon links plaatsen
        if($teller%2!=0){

            $pdf->SetFont('Arial','',12);
            $pdf->Cell(95,7,$titel,0,1);
            $y = $pdf->GetY();
            $x = $pdf->GetX();
            $pdf->SetFont('Arial','',10);
            $pdf->Cell(30,45,$pdf->Image($foto,$pdf->GetX(),$pdf->GetY(),30),1,0);
            $pdf->MultiCell(65,5,$onderelkaar,0);

        //Als de teller even is, de persoon rechts plaatsen    
        }else{

            $pdf->SetY($y-7);
            $pdf->SetX($x+95);
            $pdf->SetFont('Arial','',12);
            $pdf->Cell(95,7,$titel,0,0);
            $pdf->SetY($y);
            $pdf->SetX($x+95);
            $pdf->Cell(30,45,$pdf->Image($foto,$pdf->GetX(),$pdf->GetY(),30),1,0);
            $pdf->SetY($y);
            $pdf->SetX($x+125);
            $pdf->SetFont('Arial','',10);
            $pdf->MultiCell(65,5,$onderelkaar,0);
            $pdf->SetY($y+45);
            $pdf->SetX(10);
            $pdf->Cell(0,9,'',0,2);

        }

        //Teller laten oplopen
        $teller = $teller+1;    

    //Afsluiten van de while-loop
    }

//Afsluiten van de else
}

//Als de laatste persoon links geplaatst is, cursor naar beneden zetten (ipv ernaast)
if($teller%2==0){

    $pdf->SetY($y+45);
    $pdf->SetX(10);
    $pdf->Cell(0,9,'',0,2);

}

//PDF daadwerkelijk aanmaken
$pdf->Output();

//Statement en databaseconnectie sluiten
$stmt->close();
$con->close();

?>

When I replace the five ?'s with 'Tekenen'and remove the bind_param, the pdf is correctly rendered. When I use the code above, it doesn't. The page keeps "Loading...". I used var_dump throughout the code on every variable. I get the same output in both cases (working and not working). Can anyone help???

Edit 4

I narrowed it down to the following line (appears two times in the code.):

$pdf->Cell(30,45,$pdf->Image($foto,$pdf->GetX(),$pdf->GetY(),30),1,0);

More specific, this works:

echo '<img src="fotos/geenfoto.jpg" width=100>';

This doesn't:

$pdf->Image("fotos/geenfoto.jpg",0,0,30);

As stated earlier, it does work without using variables in de MySql(i) query, what can be wrong?

Cropje
  • 67
  • 1
  • 7
  • What exactly happens when it "doesn't work"? – Vatev Jul 13 '15 at 12:42
  • The page starts making a pdf file, but keeps "Loading...". Normally, in the loading picture, a circle consisting of eight parts fills up, when it's full, the document is ready. Now no parts are shown, just the text "Loading,..." – Cropje Jul 13 '15 at 12:46
  • dont use mysql_query, use mysqli or pdo combined with prepared statements. – Tschallacka Jul 13 '15 at 14:28
  • Please read the [huge red warning at the top of this page](http://php.net/manual/en/function.mysql-query.php) and adapt your code accordingly. – Niels Keurentjes Jul 13 '15 at 14:28
  • Ok, I know I should use mysqli instead of mysql. I would like to make it work first, then switch to mysqli. – Cropje Jul 13 '15 at 14:34
  • I feel like your problem is somewhere within "here the stuff I want to do with the results". my guess is you are trying to also use `$importsectie` within that code and it's supposed to be a different format than how you have [changed] it for your sql queries – CrayonViolent Jul 13 '15 at 14:35
  • I thought so too, but I thoroughly checked, I'm not using `$importsectie` anywhere else in the code. – Cropje Jul 13 '15 at 14:46
  • See edit 3: I switched to mysqli combined with prepared statements, but it's still not working, any idea's anyone? – Cropje Jul 13 '15 at 22:17
  • More [here](http://stackoverflow.com/questions/31397748/images-in-fpdf-using-php-and-mysqli). – Cropje Jul 14 '15 at 07:35

2 Answers2

0

Besides the all-popular recommendation for not using mysql_* functions,
you need to make sure you don't have any whitespace in your array elements.

Here's some example code to remove and debug the query at each step.

<?php

$elements = array('  element A', "\t Element B \r\n");

var_dump($elements);

/*
use var_dump to check your array elements for whitespace and such
array(2) {
  [0]=>
  string(11) "  element A"
  [1]=>
  string(14) "   Element B
"
}
*/

// create your IN clause string and verify it
$joinedString = "('" . join("','",array_map('trim',$elements)) . "')";

var_dump($joinedString);
/*
use var_dump not echo
string(25) "('element A','Element B')"

*/

// your query string finally becomes
$query = "SELECT * FROM smoelenboek 
WHERE sectie1 IN $joinedString 
OR sectie2 IN $joinedString 
OR sectie3 IN $joinedString 
OR sectie4 IN $joinedString 
OR sectie5 IN $joinedString 
AND actief='ja' ORDER BY achternaam ASC";

// and check it with var_dump and also run it in PhpMyAdmin
var_dump($query);
/*
string(280) "SELECT * FROM smoelenboek
WHERE sectie1 IN ('element A','Element B')
OR sectie2 IN ('element A','Element B')
OR sectie3 IN ('element A','Element B')
OR sectie4 IN ('element A','Element B')
OR sectie5 IN ('element A','Element B')
AND actief='ja' ORDER BY achternaam ASC"
*/
Alex Andrei
  • 7,315
  • 3
  • 28
  • 42
  • Thank you! That answer was a lot of effort! Unfortuately, it doesn't solve my problem... I get exactly the same output with `var_dump($query1)` and `var_dump($query2)`. Still, the script only works with `$query2` and without the for-loop. – Cropje Jul 13 '15 at 15:23
0

Apart from the Alex Andrei comment which is still valid I would strongly suggest to use a prepared statement instead of a plain SQL query. This is a related post about what to do (and not to do) with MySQL prepared statements and array parameters: mysqli bind_param for array of strings

Prepared statements offer "for free" a more reliable and secure dynamic parameter binding which is what you want, and also better performances especially with recurring queries because prepared statements are (pre-)compiled by the database engine and much more efficient to execute.

Community
  • 1
  • 1
m c
  • 1,104
  • 1
  • 12
  • 21
  • See edit 3: I switched to mysqli combined with prepared statements, but it's still not working, any idea's anyone? – Cropje Jul 13 '15 at 22:17
  • "Still not working" means the query does not return what you expect or returns an error? In the first case, you must be 100% sure that the SQL query with those parameters actually works fine in the first place if you run it manually using a SQL client. You can probably get back the SQL query which PHP runs behind the scenes if you turn on the debug logs. – m c Jul 14 '15 at 09:18
  • The query works fine, I checked in PhpMyAdmin. The problem seems to be in fpdf with images. See more [here](http://stackoverflow.com/questions/31397748/images-in-fpdf-using-php-and-mysqli). – Cropje Jul 14 '15 at 10:13