Displaying only selected values from database - php

<?php
$sql = "SELECT * FROM team;";
$result = mysqli_query($conn, $sql );
$row = mysqli_fetch_row($result);
$teamname = $row[1];
echo $teamname;
Consider table in DB consists of 10 names from 1-10. That will be displayed on the screen as usually (using retrieving), but the problem is when I click any name from 1-10 displaying on the screen that should open a new page by displaying only the particular name I selected.
I tried this but, all the values are displaying.

First, add to your mysql table a column called "ID" to associate a number to each name.
After you can direct the user to your page like this
Name n.1 // etc..
so you can take the id of your name using GET and display to your page only that name
(Always use Prepared Statement even when it is not strictly necessary)
PHP script
$name_id = $_GET['id'];
// connect to your db
$stmt = $db->prepare("SELECT * FROM team WHERE ID = ?");
$stmt->bind_param("s",$name_id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
echo $result['name'];
if you need anything else, comment below.

Related

Display the item selected by specific user in status page for that specific user

I would like to ask how to display the information based username? I mean when I login, it will lead me to select data page. My select data page has username, name and date. The name is the name of item in spinner, i put these item in spinner. For example, username which is john select item 1 in spinner and it will send to database. Then when go status page, it will only display the item selected by John only in John account. Same as other account, in their account only will display their own item selected.
Below is my select item php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$username = $_POST['username'];
$name = $_POST['name'];
$date = $_POST['date'];
//Creating an sql query
$sql = "INSERT INTO Selection (username, name, date) VALUES
('$username','$name', '$date')";
//Importing our db connection script
require_once('dbConnect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Selected Successfully';
}else{
echo 'Sorry, You Already Select this item';
}
//Closing the database
mysqli_close($con);
}
?>
View Status Php:
<?php
//Importing Database Script
require_once('dbConnect.php');
//Creating sql query
$sql = "SELECT * FROM Selection";
//getting result
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"id"=>$row['id'],
"username"=>$row['username'],
"name"=>$row['name'],
"date"=>$row['date']
)
);
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I am using localhost and phpmyadmin.
Table structure for Selection is below:-
id - primary key Not Null
username NOT NULL,
name NOT NULL,
date NOT NULL,
ALTER TABLE `Selection` ADD UNIQUE `unique_index`(`username`, `name`);
As you haven't mention the Schema of Spinner and Selection table, assuming a simple case for you, the solution would be like instructed below..
When user logs in, capture it's username (usually store it in session till he/she logs out).
In your Status.php your query would be
Select * from Selection where username = '$YOUR_USER_NAME_FROM_SESSION_HERE';
That should be enough as per your requirement.
NOTE: Using variable directly in your query will result in exposure of SQL injection. To prevent Sql injection, refer this answer too.
when the user logged in set the session using $_SESSION["name"] = "$username";
right now session is set then you can access the session variable from anywhere in the view page you retrieve the session using
$user= $_SESSION["name"].
now you fetch the items from the database
like
$sql = "SELECT * FROM Selection where username='$user'";
try it

Delete PHP Data from MYSQL after display

After the data is displayed I want the exact text to get deleted from MySQL
I have a random generator that gets data from a row and displays it random
Architecture :
"minecraft" and inside the table its a row named "list"
<?php
// Connect to database server
mysql_connect("localhost", "bdweb_panel", "password") or die (mysql_error ());
// Select database
mysql_select_db("bdweb_panel") or die(mysql_error());
$strSQL = "SELECT * FROM minecraft";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Array to hold all data
$rows = array();
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// add row to array.
$rows[] = $row;
}
// Close the database connection
mysql_close();
// Max rand number
$max = count($rows) - 1;
// print out random combination of data.
echo $rows[rand(0, $max)][0] . " "
?>
Update :
To be more explicit
This is the architecture from the DB
and the php page with a refresh button
Each time a user is pressing the refresh button he gets a data from the DB (EX : test1, and if he press once again test2 or test3 or test 4 - all random data) all random. Once he gets for example test 1, the text 1 data from the DB deletes so it will not be generated once more again, so after he press the refresh button he will display a data and at the same time he will delete it from the data base.
Since mysql is deprecated you should use mysqli and prepared statements;
Heres a short example how to delete a mysql entry
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$stmt = $mysqli->prepare("DELETE FROM table WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
But if you just want to delete the column of an entry you need to use an UPDATE query
$stmt = $mysqli->prepare("UPDATE table SET column = ? WHERE id = ?");
$stmt->bind_param('si',$new_value, $id);
$stmt->execute();
where $new_value can be null or whatever you want to.
If I understand correctly your question:
<?php
...
$max = count($rows) - 1;
$r = rand(0, $max);
/// if $rows[$r][0] is ID column
mysql_query("delete from minecraft where id = ".$rows[$r][0];
OR
mysql_query("update minecraft set list='' where id=".$rows[$r][0];
echo $rows[$r][0];
?>
Update :
To be more explicit
This is the arhitecture from the DB http://i.stack.imgur.com/crvh0.png and the php page with a refresh button http://i.imgur.com/F1Q3mAx.png
Each time a user is pressing the refresh button he gets a data from the DB ( EX : test1 , and if he press once again test2 or test3 or test 4 - all random data ) all random . Once he gets for example test 1 , the text 1 data from the DB deletes so it will not be generated once more again , so after he press the refresh button he will display a data and at the same time he will delete it from the data base.

Check if an user is in a database

I have developed a game with Javascript and when the user finishes it, I must save his record in a database. Here you see the code:
$temp = $_POST['playername']; //username
$text = file_get_contents('names.txt'); //list with all usernames
//this text file contains the names of the players that sent a record.
$con=mysqli_connect("localhost","username","pass","my_mk7vrlist");
if (stripos(strtolower($text), strtolower($temp)) !== false) {
//if the username is in the list, don't create a new record but edit the correct one
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
} else {
//The username is not in the list, so this is a new user --> add him in the database
mysqli_query($con, "INSERT INTO `mk7game` (`playername`,`record`,`country`,`timen`) VALUES ('".$_POST['playername']."', '".$_POST['dadate']."', '".$_POST['country']."', '".$_POST['time_e']."')");
file_put_contents("names.txt",$text."\n".$temp);
//update the list with this new name
}
//Close connection
mysqli_close($con);
When I have a new user (the part inside my "else") the code works correctly because I have a new row in my database.
When the username already exists in the list, it means that this player has already sent his record and so I must update the table. By the way I cannot edit the record on the player that has alredy sent the record.
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
It looks like this is wrong, and I can't get why. I am pretty new with PHP and MySQL.
Do you have any suggestion?
You're missing quotes around $temp in the UPDATE statement:
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game`
SET `record` = '".$_POST['dadate']."'
WHERE `mk7game`.`playername` = '".$temp."'
^ ^
LIMIT 1 ") or die(mysqli_error($con));
However, it would be better to make use of prepared statements with parameters, rather than inserting strings into the query.
Escape your user input!
$temp = mysqli_real_escape_string($con, $_POST['playername']);
Make sure to stick your mysqli_connect() above that
$select = mysqli_query($con, "SELECT `id` FROM `mk7game` WHERE `playername` = '".$temp."'");
if(mysqli_num_rows($select))
exit("A player with that name already exists");
Whack that in before the UPDATE query, and you should be good to go - obviously, you'll need to edit it to match your table setup

How do I find out a specific row ID from a table?

Hello I’m working on a project (I’m a total newbie), here ‘s how the project goes…
I’ve created a Create User page, the user puts in the credentials and click on Create Account.
This redirects to another page (process.php) where all MySQL queries are executed-
Note: ID is set to Auto Increment, Not Null, Primary Key. All the data is inserted dynamically, so I don’t know which Username belongs to which ID and so on.
$query = “INSERT INTO users (Username, Something, Something Else) VALUES (‘John’, ‘Smith’, ‘Whatever’ )”
Everything gets stored into the “users” table.
Then it gets redirected to another page (content.php) where the User can review or see his/her credentials.
The problem is, I use SELECT * FROM users and mysql_fetch_array() but it always gives me the User with ID = 1 and not the current User (suppose user with ID = 11). I have no idea how to code this.
There are suppose 50 or more rows,
how can I retrieve a particular row if I don’t know its ID or any of its other field’s value?
You may use:
mysql_insert_id();
Get the ID generated in the last query. Reference: http://us1.php.net/mysql_insert_id
This function return the ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
Now you have the id, add that to your WHERE clause.
Note: It would be better if you use mysqli.
You are using mysql_fetch_array() just once, so it is getting you just one row.
what you are writing:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo(row['id']);
?>
What should be there to fetch all the rows:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo(row['id']);
}
?>
Now, what you need, is to get the user id of the registered user at that time.
For that, you need to create a session. Add session_start(); in your process.php and create a session there. Now to get the last id you have to make a query:
select *
from users
where id = (select max(id) from users);
Now this will give you the last id created. Store that in a session variable.
$_SESSION['id']=$id;
Now, on content.php add this:
session_start();
echo($_SESSION['id']);
You have to use WHERE:
SELECT * FROM users WHERE ID = 11
If you dont use WHERE, it will select all users, and your mysql_fetch_assoc will get you one row of all (ie. where ID = 1).
PS: mysql_* is deprecated, rather use mysqli_*.
Using mysql_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysql_query($query) or die( mysql_error() );
$user_id = mysql_insert_id();
header("Location: content.php?id=".$user_id);
Or another way to pass $user_id to your next page
$_SESSION['user_id'] = $user_id;
header("Location: content.php");
Using mysqli_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysqli_query($dbConn, $query) or die( printf("Error message: %s\n", mysqli_error($dbConn)) );
$user_id = mysqli_insert_id($dbConn);

show row data from a specific ID

I'm building a simple bug tracking tool.
You can create new projects, when you create a project you have to fill in a form, that form posts to project.class.php (which is this code)
$name = $_POST['name'];
$descr = $_POST['description'];
$leader = $_POST['leader'];
$email = $_POST['email'];
$sql="INSERT INTO projects (name, description, leader, email, registration_date)
VALUES ('$name', '$descr', '$leader', '$email', NOW())";
$result = mysql_real_escape_string($sql);
$result = mysql_query($sql);
if($result){
header('Location: ../projectpage.php?id='.mysql_insert_id());
}
else {
echo "There is something wrong. Try again later.";
}
mysql_close();
(It's not yet sql injection prove, far from complete...)
Eventually you get redirected to the unique project page, which is linked to the id that is stored in the MySQL db. I want to show the name of that project on the page, but it always shows the name of the first project in the database.
(here I select the data from the MySQL db.)
$query = 'SELECT CONCAT(name)
AS name FROM projects';
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
(here I show the name of the project on my page, but it's always the name of the first project in the MySQL db)
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
How can I show the name of the right project? The one that is linked with the id?
Do I have the use WHERE .... ?
Yes, You have to use the WHERE to specify which project You want to get. I'm also not sure why are You using CONCAT function when You want to get only one project.
Other important thing is that You have to use mysql_real_escape_string() function on parameters before You put them in the query string. And use apropriate functions for specific type of data You receive.
So Your statement for getting the project should look like this:
SELECT name FROM projects WHERE id = ' . intval($_GET['id'])
Also when before You use the mysql_fetch_assoc() function, check if there are any records in the result with
if(mysql_num_rows($result) > 0)
{
$project = mysql_fetch_assoc($result);
/* $project['name'] */
}
try this
// first get the id, if from the url use $_GET['id']
$id = "2";
$query = "SELECT `name` FROM `projects` WHERE `id`='".intval($id). "'";
$result = mysql_query(mysql_real_escape_string($query));
use mysql_fetch_row, here you'll not have to loop through each record, just returns single row
// if you want to fetch single record from db
// then use mysql_fetch_row()
$row = mysql_fetch_row($result);
if($row) {
echo '<h5>'.$row[0].'</h5>';
}
$row[0] indicates the first field mentioned in your select query, here its name
The might be of assistance:
Your are currently assing a query string parameter projectpage.php?id=
When you access the page the sql must pick up and filter on the query string parameter like this:
$query = 'SELECT CONCAT(name) AS name FROM projects WHERE projectid ='. $_GET["id"];
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
Also maybe move mysql_insert_id() to right after assigning the result just to be safe.
$result = mysql_query($sql);
$insertId = mysql_insert_id();
Then when you assign it to the querystring just use the parameter and also the
header('Location: ../projectpage.php?id='.$insertId);

Categories