简体   繁体   中英

How do I convert this SQL to prepared statement?

I need help with converting this SQL to Prepared Statement. This is for my search bar. I hope I'll be able to receive some help as I am a beginner in this.

This is my SQL

$conn = mysqli_connect('localhost','root','','my_db');
            
$mysql = "SELECT * FROM catetable";
$bike_list = mysqli_query($conn,$mysql);

$catesql = "SELECT catename FROM catetable";
$cate_list = mysqli_query($conn,$catesql);

And this is what I would like to change to Prepared Statement

if (isset($_GET['search']))
{
    
    $search = $_GET['search'];
    
    $searchlist = array();
    $lowersearchlist = array();
    $i = 0;
    while ($one_cate = mysqli_fetch_assoc($cate_list))
    {
        $searchlist[$i] = $one_cate['catename'];
        $lowersearchlist[$i] = strtolower($one_cate['catename']);
        $i++;
    }
    if (in_array($search,$searchlist) || in_array($search,$lowersearchlist))
    {
        header("Location:feature.php");
    }
    else
    {
        header("Location:index.php?error=true");
        
    }
}

Write a query that matches the parameter in the WHERE clause. MySQL normally defaults to case-insensitive comparisons, so you don't need to fetch all the rows to compare them exactly and case-insensitively.

if (isset($_GET['search'])) {
    $stmt = $conn->prepare("SELECT COUNT(*) AS c FROM yourTable WHERE catename = ?");
    $stmt->bind_param("s", $_GET['search']);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    if ($row['c'] > 0) {
        header("Location: feature.php");
    } else {
        header("Location: index.php?error=true";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM