Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

php - 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");
        
    }
}
question from:https://stackoverflow.com/questions/66051001/how-do-i-convert-this-sql-to-prepared-statement

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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";
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...