read text file in php and use its content to fetch data from mysql database

I'm trying to read a text file using PHP. After I read the content I want to match the content with an existing table in mysql.

My text file has this content

           :mh2045

The file is a .txt file

I use the following php code to read the text file

            <?php
               $file =         file_get_contents("file.txt");
              ?>

How do I use the contents of $file to compare with the field "vehicleid" of table vehicle info in mysql

this is the php code for selecting records after comparing with content in $file

      <?php
       $servername = "localhost";
       $username = "root";
       $password = "password";
       $dbname = "sample";
       $file=file_get_contents("file.txt");
       @var =$file;

         // Create connection
          $conn = new mysqli($servername, $username, $password,             $dbname);
         // Check connection
         if ($conn->connect_error) {
         die("Connection failed: " . $conn->connect_error);
         } 

      $sql = "SELECT *
                   FROM vehicleinfo
                   WHERE vehicleid =    (SELECT vehicleid 
                                      FROM vehicleinfo
                                       WHERE owner= @var)";
       $result = $conn->query($sql);

      if ($result->num_rows > 0) {
       // output data of each row
     while($row = $result->fetch_assoc()) {
              echo "id: " . $row["vehicleid"]. " - Name: " .              $row["name"]. " " . $row["owner"]. "<br>";
 }
   } else {
   echo "0 results";
        }
               $conn->close();       

Upvotes: 0

Views: 3038

Answers (2)

j_s_stack
j_s_stack

Reputation: 665

For Variables in PHP use $ not @. @ is for Error Handling. With a . you can connect Strings, ist a bad Practice to write the Var into a String. And also use ' rather then " for Strings. That makes your proccesing quicker, becouse the Compiler doesn't look vor Variables in the String.

$file = file("file.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$sql = 'SELECT *
                   FROM vehicleinfo
                   WHERE vehicleid =    (SELECT vehicleid 
                                      FROM vehicleinfo
                                       WHERE owner= '. $file .')';

Upvotes: 1

Aniruddh
Aniruddh

Reputation: 7668

Get rid of the @var line and use following SQL query:

$file = file("file.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$sql = "SELECT *
                   FROM vehicleinfo
                   WHERE vehicleid =    (SELECT vehicleid 
                                      FROM vehicleinfo
                                       WHERE owner= ". $file[0] .")";

Upvotes: 0

Related Questions