Putting MySQL data from database into a variable - php

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.

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.

Related

Unique page for each row in database with PHP

I have been trying to create a unique page for each row in my database. My plan is to create a dictionary.php?word=title url, where I can display the description and title of that specific ID. My datbase is contains id, term_title and term_description.
I'm fresh outta the owen when it comes to PHP, but I've managed to atleast do this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Cannot connect to database." . mysqli_connect_error());
}
if (isset($_GET['id']))
{
$id = (int) $_GET['id'];
$sql = 'SELECT * FROM dbname WHERE id = $id LIMIT 1 ';
}
$sql = "SELECT * FROM terms";
$result = $conn->query($sql);
mysqli_close($conn);
?>
I'm really stuck and I dont know what the next step is, I've added the <a href='dictionary.php?=".$row["id"]."'> to each word I want to be linked, and this is properly displayed in the main index.php file (where all my words are listed with <li>. This is my code for this:
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<a href='dictionary.php?=".$row["id"]."'><li class='term'><h4 class='term-title'>" . $row["term_title"]. "</h4></li></a>";
} else {
echo "No words in database.";
}
?>
How do I create this unique page, only displaying title and description for that id? How do I add ?word= to the url?
Thanks for taking your time to help me.
Update from years later: Please, please use parameters when composing your SQL queries. See Tim Morton's comment.
You're on the right track, and ajhanna88's comment is right, too: you want to be sure to include the right key ("word" in this case) in the URL. Otherwise, you're sending a value without telling the page what that value's for.
I do see a couple other issues:
When you click on one of the links you created, you're sending along $_GET["word"] to dictionary.php. In your dictionary.php code, however, you're searching for your word by "id" instead of by "word". I'm guessing you expect users to search your dictionary for something like "celestial" and not "1598", so try this instead:
if (isset($_GET['word'])) {
$word = $_GET['word'];
$sql = 'SELECT * FROM dbname WHERE word = $word LIMIT 1 ';
}
BUT! Also be aware of a security problem: you were letting the user put whatever they want into your query. Take a look at the classic illustration of SQL injection. To fix that, change the second line above to this:
`$word = $conn->real_escape_string($_GET['word']);`
Another problem? You're looking for the word exactly. Instead, you'll probably want to make it case insensitive, so "Semaphore" still brings up "semaphore". There are plenty of ways to do that. The simplest way in my experience is just changing everything to lowercase before you compare them. So that $word assignment should now look like this:
`$word = $conn->real_escape_string(strtolower($_GET["word"]));`
And your query should look something like this:
`$sql = "SELECT * FROM dbname WHERE word = LOWER('$word') LIMIT 1 ";`
Next! Further down, you overwrite your $sql variable with SELECT * FROM terms, which totally undoes your work. It looks like you're trying to show all the words if the user doesn't provide a word to look up. If that's what you're trying to do, put that line in an else statement.
Your $result looks fine. Now you just have to use it. The first step there is to do just like you did when you tested the connection query (if(!$conn)...) and check to see that it came back with results.
Once you have those results (or that one result, since you have LIMIT 1 in your query), you'll want to display them. This process is exactly what you did when printing the links. It's just that this time, you'll expect to have only one result.
Here's a real basic page I came up with from your code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$conn=new mysqli($servername,$username,$password,$dbname);
if($conn->connect_errno){
die("Can't connect: ".$conn->connect_error);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Dictionary!</title>
</head>
<body>
<?php
if(isset($_GET["word"])){
$word = $conn->real_escape_string(strtolower($_GET["word"]));
$sql = $conn->query("SELECT * FROM dictionary WHERE word=LOWER('".$word."') LIMIT 1");
if(!$sql){
echo "Sorry, something went wrong: ".$conn->error_get_last();
} else {
while($row=$sql->fetch_assoc()){
echo "<h2>".$row["word"]."</h2>";
echo "<p>".$row["definition"]."</p>";
}
}
} else {
$sql = $conn->query("SELECT word FROM dictionary");
if(!$sql){
echo "Sorry, something went wrong: ".$conn->error_get_last();
} else {
echo "<p>Here are all our words:</p><ul>";
while($row=$sql->fetch_assoc()){
echo "<li>".$row["word"]."</li>";
}
}
echo "</ul>";
}
?>
</body>
</html>
You should also take care to be consistent in your terminology. For this, my MySQL table had three columns: id, word, and definition. I dropped term since your URLs were using word. In my experience, it's best to keep the same terminology. It avoids confusion when your application gets more complicated.
Lastly, to answer your question about creating separate pages, you can see there that for a simple page like this, you may not need a separate page to display the definitions and the links -- just an if/else statement. If you want to expand what's in those if/else blocks, I'd suggest looking at PHP's include function.
You have a great start. Keep at it!

PHP login script using bind_result in subsequent query mysqli

I'm trying to build a relatively simple PHP login script to connect to MySQL database running on my home server. I know the connection works as I've gotten some data returned as I would expect. However, I am having trouble getting the full script to work.
Essentially, I'm taking in a username/password from the user, and I first do a lookup to get the user_id from the users table. I then want to use that user_id value to do a comparison from user_pswd table (i'm storing usernames and passwords in separate database tables). At one point, I was able to echo the correct user_id based on the username input. But I haven't been able to get all the issues worked out, as I'm pretty new to PHP and don't really know where to see errors since I load this onto my server from a remote desktop. Can anyone offer some advice/corrections to my code?
The end result is I want to send the user to another page, but the echo "test" is just to see if I can get this much working. Thanks so much for the help!
<?php
ob_start();
$con = new mysqli("localhost","username","password","database");
// check connection
if (mysqli_connect_errno()) {
trigger_error('Database connection failed: ' . $con->connect_error, E_USER_ERROR);
}
$users_name = $_POST['user'];
$users_pass = $_POST['pass'];
$user_esc = $con->real_escape_string($users_name);
$pass_esc = $con->real_escape_string($users_pass);
$query1 = "SELECT user_id FROM users WHERE username = ?;";
if ($result1 = $con->prepare($query1)) {
$result1->bind_param("s",$user_esc);
$result1->execute();
$result1->bind_result($userid);
$result1->fetch();
$query2 = "SELECT user_pswd_id FROM user_pswd WHERE active = 1 AND user_id = ? AND user_pswd = ?;";
if ($result2 = $con->prepare($query2)) {
$result2->bind_param("is",$userid,$pass_esc);
$result2->execute();
$result2->bind_result($userpswd);
$result2->fetch();
echo "test", $userpswd;
$result2->free_result();
$result2->close();
} else {
echo "failed password";
}
$result1->free_result();
$result1->close();
}
$con->close();
ob_end_clean();
?>

how to update multiple data using php

i am a newbie in here and i have a problem that me myself cannot find the exact solution... here it is... i need to build a system that will update all the staff information. through this system, a staff in human resource department will enter all the staffs information. i have been create this code to update the staffs information but it seems not function with what i really want.... i just want to update by rows however, it turns to update all rows in the database...
<?php
session_start();
include ("includes/database.php");
include ("includes/security.php");
include ("includes/config.php");
$nama=$_SESSION["nama"];
$pwd=$_SESSION["status"];
$nama=$_POST["st_nama"];
$siri1=$_POST["st_siri"];
$siri2=$_POST["st_siri2"];
$siri3=$_POST["st_siri3"];
$jawatan=$_POST["st_jawatan"];
$gred=$_POST["st_gred"];
$gredh=$_POST["st_gredh"];
$gelaran=$_POST["st_gelaran"];
$elaun=$_POST["st_elaun"];
$id=$_GET["id"];
$dataPengguna2= mysql_query("SELECT * FROM tbl_rekod where id='$id'");
mysql_query("UPDATE tbl_rekod set st_nama='$nama', st_siri='$siri1', st_siri2='$siri2', st_siri3='$siri3', st_jawatan='$jawatan', st_gred='$gred', st_gredh='$gredh', st_gelaran='$gelaran', st_elaun='$elaun' WHERE id='$id'") or die (mysql_error());
$status = "REKOD BERJAYA DIKEMASKINI!<br/><a href = 'stafflogin.php'><strong>KEMBALI KE LAMAN UTAMA</strong></a>";
?>
This will help fix your sql injection issue, and may also fix update 1 vs multiple rows issue. This method uses the PDO library in PHP. You can see more info on using PDO on the PHP site. It replaces the mysql_ set of commands which are no longer included in the PHP releases.
// Below replaces the mysql_connect() so it requires db credentials filled in
try {
$host = 'hostname';
$db = 'databasename';
$user = 'username';
$pass = 'password';
$con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
// This replaces the die("error message") potion of a mysql_connect() set-up
catch (Exception $e) {
$_errors['connect']['message'] = $e->getMessage();
$_errors['connect']['error_code'] = $e->getCode();
}
$nama = $_SESSION["nama"];
$pwd = $_SESSION["status"];
$nama = $_POST["st_nama"];
$siri1 = $_POST["st_siri"];
$siri2 = $_POST["st_siri2"];
$siri3 = $_POST["st_siri3"];
$jawatan = $_POST["st_jawatan"];
$gred = $_POST["st_gred"];
$gredh = $_POST["st_gredh"];
$gelaran = $_POST["st_gelaran"];
$elaun = $_POST["st_elaun"];
$id = $_GET["id"];
// You should do just a preliminary check that the id is a numeric value
// No sense in continuing if someone tries to foil the natural
// order of your code
if(is_numeric($id)) {
// The next 3 lines would be equivalent to the mysql_query("statement here")
// as well as a more robust version of mysql_real_escape_string(). It does more,
// but for sake of explanation it does that and more.
$dataPengguna2 = $con->prepare("SELECT * FROM tbl_rekod where id=:id");
// Binding paramaters basically sanitizes the value being inserted into your query
$dataPengguna2->bindParam(':id',$id);
$dataPengguna2->execute();
// There is no indication of what you are doing with the select above
// Set up the update statement
$query = $con->prepare("UPDATE tbl_rekod set st_nama=:st_nama, st_siri=:st_siri, st_siri2=:st_siri2, st_siri3=:st_siri3, st_jawatan=:st_jawatan, st_gred=:st_gred, st_gredh=:st_gredh, st_gelaran=:st_gelaran, st_elaun=:st_elaun WHERE id=:id");
// Bind all the values to sanitize against injection
// You could do a function that loops through an array of values,
// but this is one way to do it manually
$query->bindParam(':st_nama',$nama);
$query->bindParam(':st_siri',$siri1);
$query->bindParam(':st_siri2',$siri2);
$query->bindParam(':st_siri3',$siri3);
$query->bindParam(':st_jawatan',$jawatan);
$query->bindParam(':st_gred',$gred);
$query->bindParam(':st_gredh',$gredh);
$query->bindParam(':st_gelaran',$gelaran);
$query->bindParam(':st_elaun',$elaun);
$query->bindParam(':id',$id);
$query->execute();
// Print out error info. There may be something of value here
// that may help you figure out why it's trying to update all your rows
// instead of just the one.
print_r($query->errorInfo());
$status = "REKOD BERJAYA DIKEMASKINI!<br/><a href = 'stafflogin.php'><strong>KEMBALI KE LAMAN UTAMA</strong></a>";
} ?>

Fetch results from database with mysqli prepared statements

I tried to fetch results from database with mysqli prepared statements and I wanted to store it in session, but I failed. I want to store id, username, password and mail to session. Can anyone review my code?
$kveri = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$kveri->bind_param('ss', $username, $password);
$kveri->execute();
$kveri->store_result();
$numrows = $kveri->num_rows;
if ( $numrows == 1 )
{
$kveri->bind_result($user_id, $user_username, $user_password, $user_mail);
while ( $kveri->fetch() )
{
$_SESSION['ulogovan'] = true;
$_SESSION['username'] = $user_username;
}
$kveri->close();
echo $_SESSION['username'];
}
Make sure you have turned on error reporting as follows:
mysqli_report(MYSQLI_REPORT_ALL);
You are likely to get the answer there. I ran your code flawlessly and it should work.
Note, I added the following code to the beginning to test (with constants defined but not shown here):
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS,DB_NAME);
As you can see, mysqli is quite inconvenient, if used as is. Thousand tricks, nuances and pitfalls.
To make database interactions feasible, one have to use some sort of higher level abstraction, which will undertake all the repeated dirty job.
Out of such abstractions PDO seems most conventional one:
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->execute([$username, $password]);
$user = $stmt->fetch();
if ($user) {
$_SESSION['username'] = $user['username'];
}
see - when used wisely, a code not necessarily have to be of the size of "War and Peace"

Login Script working local but not on live environment

I seem to have a problem with a login script, it works on a local php dev box, but not on my live environment, i'm assuming i'm missing something can anyone advise further?
<?php
$user = $_POST["swtorun"];
$pass = $_POST["swtorpw"];
// Generate hash
$enc_pwd = hash('sha256', $pass);
// Connect to DataBase
include('../../settings.php');
$conn = mysql_connect($host,$username,$password);
$db = mysql_select_db($database, $conn);
// mySql Query users
$sql = "SELECT * FROM `users` WHERE username='$user' and password='$enc_pwd'";
$result = mysql_query($sql, $conn);
$count = mysql_num_rows($result); // number of results (should be 1)
if($count==1){
// initiate session
session_start();
$_SESSION['logged'] = "1";
echo "you are now logged in, return to the index";
} else {
echo "Wrong Username or Password";
}
?>
Add session_start(); to the topmost part of your PHP code.
The issue turned out to be that I had the table name capitalised on one script, but lower case on this script, hence the query failed and so did the code relying on it, I have since fixed the other script to create the table in lower case.
thanks to all commments left in helping troubleshooting issue.

Categories