douqinlu4217 2015-09-06 18:18
浏览 79
已采纳

将数据库中的MySQL数据放入变量中

I'm making a luck based website and I want to make sure they have enough spins on their account before they spin.

I did see http://www.w3schools.com/php/php_mysql_select.asp but its not really what I'm looking for.

I have these rows with the names: id username email password spins.

I can deduct amounts from spins but I can't put the exact amount of their spins on a PHP variable to put in a $SESSION for a different page.

Here's how much I have so far.

$numSpin = "SELECT * FROM $tbl_name WHERE spins";

Then put it in a $SESSION

$_SESSION['spinNum'] = $numSpin;

How would I go on to doing this? This does not work as is.

  • 写回答

1条回答 默认 最新

  • donglanying3855 2015-09-06 20:02
    关注

    Welcome to SO.

    It seems as if you are extremely new to coding so I'll try to help you out.

    Here is the code you can use and I'll explain below.

    <?php
    session_start();
    $host = 'localhost'; $db = 'db-name'; $user = 'db-user'; $pw = 'db-pwd';
    $conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    try {
        $tbl_name = 'table-name-here';
        $un = $username;
        $sql = "SELECT * FROM $tbl_name WHERE username=:un";
        $query = $conn->prepare($sql);
        $query->bindValue(':un', $un, PDO::PARAM_STR);
        $query->execute();
        $row = $query->fetch(PDO::FETCH_ASSOC);
        $totalRows = $query->rowCount();
    } catch (PDOException $e) {
        die("Could not get the data: " . $e->getMessage());
    }
    $_SESSION['spinNum'] = $row['name-of-your-field-with-spin-numbers'];
    ?>
    

    Then...

    if($_SESSION['spinNum'] >= 1) {
        // allow them to do something
    } else {
        echo "I'm sorry. It looks like you don't have any spins left. Please try again later.";
    }
    

    This code is written using pdo_mysql. You might want to read up on it here.

    Line 2 starts your session

    Lines 3-5 creates a connection to your database. Make sure to replace "db-name", "db-user" & "db-pwd" with your information.

    On line 8 replace "table-name-here" with your database table name

    On line 9 you can set "10" to whatever minimum number you want to make sure the account holder has.

    On line 19 change "name-of-your-field-with-spin-numbers" to the actual name of the field in your database table that stores the account users available spins.

    Now you can use $_SESSION['spinNum'] on your other pages.

    Don't forget to use session_start(); at the top of any page where you want to use session variables.

    Happy coding!

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部