Home > Mobile >  Do not execute the command or for SQL PHP code
Do not execute the command or for SQL PHP code

Time:05-02

Why does the following code not work when I use the command or?

<?php
include "connect.php";
$sort=$_POST["sort"];

$query="SELECT * FROM product WHERE $sort='0' ORDER BY id DESC OR $sort='1' ORDER BY id ASC ";
$stmt = $conn->prepare($query);
$stmt->execute();
$product=array();
while ($row=$stmt->fetch(PDO::FETCH_ASSOC)){
    $record["id"]=$row["id"];
    $record["title"]=$row["title"];
    $product[]=$record;
}
echo JSON_encode($product);

CodePudding user response:

What is it you're trying to attempt here? It looks like you're trying to dump an if else statement within the sql query. That's not the correct way to do it. If I'm correct with what Im saying. You can try something like this

if (Something == SomethingElse) {
$query="SELECT * FROM product WHERE $sort='0' ORDER BY id DESC"
} else {
$query="SELECT * FROM product WHERE $sort='1' $sort='1' ORDER BY id ASC"
}

Something along those routes. Also, I highly suggest you use a foreach statement for your rows instead of assigning them individually.

$query="SELECT * FROM product WHERE $sort='0' ORDER BY id DESC"

foreach ($query as $row) {
    $row["id"];
    $row["title"];
}

Remember this is just an example, so you'll have to work out the rest of the code yourself. Since you shared so little of what these variables exactly mean its hard for me to understand what you precisely want.

More about Foreach

CodePudding user response:

I think that you can't do that you want to do. You can't change the order of SELECT using OR. The OR is only for WHERE statement. You can try to create one QUERY and next using IF to make one or another query with the wish ORDER BY.

(Another thing, be carefully with inject string from POST directly to your SQL it is very insecure)

  • Related