php - 根据字段值传递数据库字段 ID 的运行 SQL

标签 php jquery mysql ajax database

我正在尝试构建一个 CMS,我可以在其中单击一个星形图标,它会更改我数据库中的 art_featured 值,假设 art_featured 值为 0然后我单击我的星形图标 我想将字段的值从 0 更改为 1。我有点让它工作,但我不知道如何传递 art_featured 值,通常我会在我的 span 上使用 id 但我已经在使用它,所以我可以知道我需要更改哪篇文章,那么我如何才能获得 art_featured 的值 到我的 SQL 语句,这样我就可以运行一个 if 和 else 语句,然后根据 art_featured 的值运行某个 SQL 语句>,

在此先感谢您的帮助!

表格

art_id  art_title  art_company    art_featured
1       lorem 1    lorem ipsum 1  1
2       lorem 2    lorem ipsum 2  0

HTML/PHP

<section class="row">
    <?php
    $sql_categories = "SELECT art_title, art_company, art_id, art_featured FROM app_articles"; 

        if($result = query($sql_categories)){
            $list = array();

            while($data = mysqli_fetch_assoc($result)){
                array_push($list, $data);
            }

            foreach($list as $i => $row){ 
            ?>
                <div class="row">
                    <div class="column two"><p><?php echo $row['art_title']; ?></p></div>
                    <div class="column two"><p><?php echo $row['art_company']; ?></p></div>
                    <div class="column one"><span id="<?php echo $row['art_id']; ?>" class="icon-small star"></span></div>
                </div>
            <?php
            }
        }
        else {
            echo "FAIL";
        }
    ?>
    </section>

j查询

        $(".star").click(function(){

        var art_id = $(this).attr('id');

        $.ajax({
        type: "POST",
        data: {art_id:art_id},
        url: "ajax-feature.php",
        success: function(data){
            if(data != false) {

            } 
            else {

            }  
        }
        });

    });

MySQL/PHP

    if(isset($_POST['art_id'])) {



    $sql_articles = "UPDATE `app_articles` SET `art_featured` = 1 WHERE `art_id` =".$_POST['art_id'];

    if(query($sql_articles)) {
        echo "YES";
    }
    else {
        echo "NO";
    }
}
else {
    echo "FAIL";
}

最佳答案

$sql_detail = "SELECT * FROM app_articles
WHERE art_id = " . $_POST['art_id'];
$sql_result = mysql_query($sql_detail);
if(mysql_num_rows($sql_result) > 0) { // the art_id supplied exists

    while($sR = mysql_fetch_array($sql_result)) {

        $art_title = $sR['art_title'];
        $art_company = $sR['art_company'];
        $art_featured = $sR['art_featured];

        // Do whatever you want with these variables

    }

} else { // the art_id supplied does not exist

} 

将 $_POST['art_id'] 直接传递到 SQL 语句中是不安全的,因此您可能应该阅读有关数据清理的内容。但这应该可以。

关于php - 根据字段值传递数据库字段 ID 的运行 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15626851/

相关文章:

php - 通过sql导入/导出magento类别

php - SQLite : GROUP BY without Aggregate

php - MySQL SELECT 将列添加到查询(如果未选择)

Jquery改变类

python - 根据过滤器使用 sqlalchamey 选择特定列值

php - 如何使用我登录的用户名将 MySQL 中的数据显示到 Android TextView?

javascript - 在 Div 中独立包装 li 列表时遇到问题

javascript - 覆盖动态 iframe 的样式

php - 如何使用 Laravel 中的现有方法更新表值?

mysql - 两个可能表的外键