将数据库中的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.
我正在建立一个基于运气的网站,我想确保他们在旋转之前在他们的帐户上有足够的旋转 。 p>
我确实看到了 http://www.w3schools.com /php/php_mysql_select.asp 但它并不是我想要的。 p>
我有这些行的名称:id username email password spins。 p>
我可以从旋转中扣除金额,但我不能将其旋转的确切数量放在PHP变量上以放入$ SESSION以用于其他页面。 p>
这是我到目前为止的数量。 p>
$ numSpin =“SELECT * FROM $ tbl_name WHERE spins”;
code> pre>
然后把它放在$ SESSION p>
$ _ SESSION ['spinNum'] = $ numSpin;
code> pre>
我将如何继续这样做? 这不起作用。 p>
div>
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!