PHP MySQL PDO TextArea Where clause with condition checks

对着背影说爱祢 提交于 2019-12-10 21:20:03

问题


I have a page as shown in the screenshot below. The idea is to enter the bus number and the list of all stops on a particular route, one per line.

The stops are already stored in a database table called 'stops' I need the ID of each stop from the textarea. My current code only gets the ID of the last stop in the textarea. I feel like I am missing something. 'busnumber' is my textfield and 'busroute' is my textarea. I would appreciate if anyone can point me out on what I need to change in order to get the ID of each stop entered in the textarea as an array. Thanks for your time in advance.

try {
            $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
            if(isset($_POST["busnumber"]) && isset($_POST["busroute"])){

            $stops = explode(PHP_EOL, $_POST["busroute"]);
            $stopsArray = '"' . implode('","', $stops) . '"';
            $sql = "SELECT * FROM stops WHERE stop_name IN ($stopsArray)";
            echo $sql."</br>";
            $query = $conn->prepare($sql);
            $query->execute();
            $query->setFetchMode(PDO::FETCH_ASSOC);
            $results = $query->fetchAll();
            foreach($results as $result){
            echo $result['stop_id'].' '.$result['stop_name'].'</br>';
            }
            }

} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());

}

UPDATE 1 I changed the code as follows

$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
        if(isset($_POST["busnumber"], $_POST["busroute"])){

    $stops = explode(PHP_EOL, $_POST["busroute"]);

    foreach($stops as $stop){
        $sql = "SELECT * FROM stops WHERE stop_name = '".$stop."'";
        $statement = $conn->query($sql);
        echo $sql.'</br>';
        $statement->setFetchMode(PDO::FETCH_ASSOC);
        $results = $statement->fetchAll();
        foreach($results as $result){
            echo $result['stop_id'].' '.$result['stop_name'];
        }
        $statement = null;

    }
        }

and still get the same output, it only gives me the ID of the last item inside the textarea


回答1:


I just realized that you have working code displayed above. I'm sorry for giving answers before (see history if ya want) that are already there above (*haha). Here, I've updated the code of yours (the first one). I changed the part where you display the result:

try {
        $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
        if(isset($_POST["busnumber"]) && isset($_POST["busroute"])){
            $stops = explode(PHP_EOL, $_POST["busroute"]);
            $stopsArray = '"' . implode('","', $stops) . '"';

            $sql = "SELECT * FROM stops WHERE stop_name IN ($stopsArray)";
            $query = $conn->prepare($sql);
            $query->execute();

            if ($query->rowCount() > 0){
                while ($row = $query->fetch(PDO::FETCH_ASSOC)){
                    echo '<br/>'.$row['stop_id'].' '.$row['stop_name'];
                }
            }else{
                echo "No records found...";
            }
        }
} catch (PDOException $pe) {
    die("Could not connect to the database $dbname :" . $pe->getMessage());
}

Note: As I have read some tutorials, using while loop is conventional than fetchAll().




回答2:


Your db structure could help to give you a more precise info. Since it is lacking, I am going to speculate over it a little just to give you an idea.

Each bus (route) has several stops. That means there must be a foreign key defined in stops table and it points to route table.

In order to select all stops from stops table on a given route, what you need to do is to modify your select statement as follows:

Semantic code

SELECT * from stops where stops.routeId = <aGivenRouteId>

or

SELECT * from stops where stops.routeId in (an Array Of Route IDs)

Keep in mind that second form is slower.

I hope it makes sense to you.

__UPDATE__

If this is the case, there might be a many to many relationship. If this is the case, look for another table which connects stops and routes. That table should contain just route_id and stop_id in order to associate them to each other. From that table, you can select stop_ids on a given route, and then from stops table you can get names of the stops.

Hope it helps.

__UPDATE2__

Oh I see. You may need to modify your screen a bit. Something like this:

+Add Route-----------------------------------------+
|Bus Number                                        |
|__________                                        |
|                                                  |
|Stops In This Route              All Stops        |
+--------------------------+-+--+------------------+
|Stop 2                    |x|  |Stop 1            |
|Stop 5                    |x|  |Stop 2            |
|Stop 9                    |x|<<|Stop 3            |
|                            |  |Stop 4           V|
+--------------------------+-+--+------------------+
|Add Route                                         |
+----------------------------+--+------------------+

In All Stops part, you can show all the stops in DB (in your stops table). For stops in this route part, I suggest you to create another table where you associate stops and routes, basically a table containing stop_id and route_id.

Would it work for you this way?




回答3:


I FIXED THE ERROR. The solution for anyone out there is simple, the PHP explode function was used to split the contents of a textarea into separate lines but it doesn't work if you use explode() with PHP_EOL. PHP EOL tells you the server's newline character from what I understand. I used the preg_split instead to perform the splitting and it works on both my localhost that runs on Windows and my server that runs on Linux. Thank you everyone for your help!!!

$conn = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                if(isset($_POST["busnumber"], $_POST["busroute"])){
                    $stops = preg_split("/\\r\\n|\\r|\\n/", $_POST['busroute']);
                    $sql = 'SELECT * FROM stops WHERE stop_name LIKE :stop';
                    $statement = $conn->prepare($sql);
                    foreach($stops as $stop){
                        $statement->bindValue(':stop', $stop);
                        $statement->execute();
                        while($result = $statement->fetch()){
                            echo $result['stop_id'].' '.$result['stop_name'].'</br>';
                        }
                    }
                }



回答4:


$conn = new PDO("mysql:host=$host;dbname=$db;charset=$charset",$user,$pass);

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);         

if(isset($_POST["busnumber"], $_POST["busroute"]))
{
                $stops = preg_split("/\\r\\n|\\r|\\n/$_POST['busroute']);
                $sql = 'SELECT * FROM stops WHERE stop_name LIKE :stop';
                $statement = $conn->prepare($sql);
                foreach($stops as $stop){
                    $statement->bindValue(':stop', $stop);
                    $statement->execute();
                    while($result = $statement->fetch())
                  {
                     echo $result['stop_id'].' '.$result['stop_name'].'</br>';                        
                  }

}               


来源:https://stackoverflow.com/questions/37560463/php-mysql-pdo-textarea-where-clause-with-condition-checks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!