Possible to have Mysql table with 2 unique columns - php

I currently save game scores using this code:
function SubmitScore()
{
global $result, $db;
$playername = $db->real_escape_string(strip_tags($_POST["playername"]));
$score = $db->real_escape_string(strip_tags($_POST["score"]));
$fbusername = $db->real_escape_string(strip_tags($_POST["fbusername"]));
$gamelevel = $db->real_escape_string(strip_tags($_POST["gamelevel"]));
$query1 = "SELECT * FROM leaderboard WHERE playername = '$playername'";
$query2 = "INSERT INTO leaderboard (playername, score,fbusername,gamelevel) VALUES ('$playername', $score,'$fbusername','$gamelevel')";
$query3 = "UPDATE leaderboard SET score = $score WHERE playername = '$playername'";
$scores = $db->query($query1);
if ($scores->num_rows == 0)
{
$db->query($query2);
$result = "0:New entry";
}
else
{
$row = $scores->fetch_object();
$oldscore = $row->score;
if ($score > $oldscore)
{
$db->query($query3);
$result = "0:Successful update";
} else
$result = "0:Score was lower than before";
}
}
The playername column is unique and inserts a new row for a new player but only updates an existing players score if it is higher than the existing one.
This is fine just for high scores and one level but I need to also need to store the users facebook name and the multipule game levels.
Is it possible to have playername and gamelevel columns to be unique, whereby I can obtain player 1 level 1, player 1 level 2 etc;
bearing in mind I also have to keep the high score as well.
John

MySQL supports a combination of columns to be defined as a unique key. If you remove the index for playername and add a new one for playername+level you are set as far as MySQL goes.
This is how it's done with SQL:
ALTER TABLE `leaderboard` DROP INDEX `unique_index`;
ALTER TABLE `leaderboard` ADD UNIQUE `unique_index`(`playername`, `gamelevel`);

Related

Accessing two different tables for one loop

I have a small issue that I can't figure out.
I have to pull data from two different tables, in one loop. I've never done that before, so I have no idea how. I tried two different queries. That looked like this:
$query = "SELECT * FROM colors ";
$color_select = mysqli_query($connection, $query);
$second_query = "SELECT * FROM votes";
$vote_select = mysqli_query($connection, $second_query);
And then put them into a loop:
while($row = mysqli_fetch_assoc($color_select) && $second_row = mysqli_fetch_assoc($vote_select))
{
$color = $row['Colors'];
$votes = $second_row['Votes'];
echo "<tr><td>$color</td><td>$votes</td></tr>";
}
But that didn't work. I didn't expect it to, just wanted to try. :) Maybe someone experienced can help me out. Thanks.
At the end of the day I need a table displayed, that has two columns, one of them contains the color name from one DB table and the other one contains a number of votes.
As requested: table structures.
Table: colors has only one field Colors.
Table: votes has four fields city_id, City, Colors and Votes
*************************EDIT**************************************
So fixed up the query as suggested, but is still shows nothing.
Here is the edited code:
$query = "SELECT * FROM colors,votes WHERE colors.Colors=votes.Colors";
$color_votes_select = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($color_votes_select))
{ $color = $row['Colors'];
$votes = $row['Votes']; }
if table having relation.
try this in single query .
SELECT
`colors`.*,votes.*
FROM
`colors`
INNER JOIN
`votes` ON
`votes`.colorId = `colors`.Id
Most imp *****You should have some relationship between tables
Otherwise workaround
Run query on color, Save it in ArrayA
Run query on vote, Save it in ArrayB
Create New Array ArrayC
$arrayC = array();
Loop array A or C if they both contact same row count
array_push($ArrayC, key and value of color, key and value of votes);
Final loop ArrayC to print tr and td
First Relate These two tables, write color_id in votes table.
$query = "SELECT * FROM colors,votes where colors.id=votes.color_id";
$color_select = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($color_select))
{
$color = $row['Colors'];
$votes = $row['Votes'];
}
Try this:
$query = "SELECT colors FROM colors";
$color_select = mysqli_query($connection, $query) or die (mysqli_error());
$second_query = "SELECT votes FROM votes"; //you only need column votes right?
$vote_select = mysqli_query($connection, $second_query) or die (mysqli_error());;
while( $row = mysqli_fetch_assoc($color_select) && $second_row = mysqli_fetch_assoc($vote_select)){
$color[] = $row['colors'];
$votes[] = $second_row['votes'];
echo "<tr><td>$color</td><td>$votes</td></tr>";
}
Short explanation:
It will fetch the select and store into an array (because what you were doing is selecting multiple rows into one single variable) and then just display with the echo.

How to Unlink a File from Website's Folder when MSSQL Table Row is Deleted Using PHP

I am trying to make the link <a href='{$_SERVER['PHP_SELF']}?del=true&orderid={$row['orderid']}' style='color:black;' onclick='return show_confirm();'>Delete</a>
delete the specific row from the MSSQL table using the while function. Currently, the bottom code works fine and deletes the specific row from the table, but I would now like it to unlink a file from the sharedstorage folder. The file that gets unlinked has it's filename stored in the name column for that table row. Each table row has a name column that contains a unique file's name from the file that is located in the sharedstorage folder.
My problem in simple terms is when a table row gets deleted, the file for that row in my website's sharedstorage folder remains and does not get deleted with the row.
Here is the code for when the delete link is hit for that specific row:
// delete from table
if ($_GET['del'] == 'true') {
// cast id as int for security
$id = (int) $_GET['orderid'];
// delete row from table
$sql = "DELETE FROM shareddrive WHERE orderid = '$id'";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// select the info, ordering by usort
$sql = "SELECT orderid, name, type FROM shareddrive ORDER BY orderid";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// initialize a counter for rewriting usort
$job_pos_sortt = 1;
// while there is info to be fetched...
while ($r = mssql_fetch_assoc($result)) {
$job_poss = $r['orderid'];
// update the usort number to the one in the next number
$sql = "update shareddrive SET orderid = '$job_pos_sortt' WHERE name = '$job_poss'";
$update = mssql_query($sql, $conn) or die(mssql_get_last_message());
// inc to next avail number
$job_pos_sortt++;
} // end while // end if del
}
All help is greatly appreciated.
// delete from table
if ($_GET['del'] == 'true') {
// cast id as int for security
$id = (int) $_GET['orderid'];
// delete row from table
$file = mssql_fetch_array(mssql_query("select name from shareddrive where orderid = $id"));
unlink($file[0]);
$sql = "DELETE FROM shareddrive WHERE orderid = '$id'";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// select the info, ordering by usort
$sql = "SELECT orderid, name, type FROM shareddrive ORDER BY orderid";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// initialize a counter for rewriting usort
$job_pos_sortt = 1;
// while there is info to be fetched...
while ($r = mssql_fetch_assoc($result)) {
$job_poss = $r['orderid'];
// update the usort number to the one in the next number
$sql = "update shareddrive SET orderid = '$job_pos_sortt' WHERE name = '$job_poss'";
$update = mssql_query($sql, $conn) or die(mssql_get_last_message());
// inc to next avail number
$job_pos_sortt++;
} // end while // end if del
}

PHP MySQL if equals else INSERT

I Have the following code:
<?php
error_reporting(E_ALL);
// connect to your MySQL database here
$dbhandle = mysql_connect('xxx', 'xxxx', 'xxxx');
$selected = mysql_select_db("xxxx",$dbhandle);
// Get the winner data
function setWinner(){
$sql = 'UPDATE user SET winner = 1 WHERE id=(SELECT id FROM user ORDER BY RAND())';
$query = mysql_query($sql) or die (mysql_error());
echo $query;
}
// Get the winner data
function getWinner()
{
$sql = 'SELECT id, fullname, email, number FROM user WHERE winner = 1';
$query = mysql_query($sql) or die (mysql_error());
if(mysql_num_rows($query) == 1) {
$user = mysql_fetch_assoc($query);
} else {
// If there is no winner yet, automatically create one
setWinner();
// Recall the function which should now find a winner
$user = getWinner();
}
return $user;
}
$winner = getWinner();
print_r($winner);
?>
Trying to work with g4vroche's answer but getting this error: You can't specify target table 'user' for update in FROM clause
I used this for a competition to select a random user from the database, but i now need it to look through all the users to see if there's a user that's winner column equals 1 and if there isn't one it should select the random user and update that users winner column with 1.
Any Help greatly appreciated.
I'm using the mysql_query() function just because you used it in your example. You should read up on PDO and implement that instead.
Per my comment above,
require_once "connect_to_mysql.php";
// look for records with `winner` set to 1
$result = mysql_query('SELECT id, fullname, email, number FROM user WHERE winner = 1 LIMIT 1') or die (mysql_error());
if (mysql_num_rows($result) < 1) { // if no records were found, pick a random row
$result = mysql_query('SELECT id, fullname, email, number FROM user ORDER BY RAND() LIMIT 1');
}
I don't know what your winner column actually stores, but assuming it's a boolean, which may contains only 0 or 1, you could do this in a single query :
SELECT id, fullname, email, number FROM user ORDER BY winner DESC, RAND() LIMIT 1;
Which will :
Sort all records on winner column, making rows hanving winner = 1 firsts
Sort equals records with RAND()
So you will get and random result, priority being given to records having winner column equals to "1".
EDIT
I missunderstood your need.
You have two different process here
Get the winner
Set the winner
You should probably split that into two function / methods
// Get the winner data
function getWinner()
{
$sql = 'SELECT id, fullname, email, number FROM user winner=1';
$query = mysql_query($sql);
mysql_num_rows($result) == 1) {
$user = mysql_fetc_assoc($query);
return $user;
}
return false;
}
function setWinner()
{
$sql = 'UPDATE user SET winner=1 ORDER BY RAND() LIMIT 1';
mysql_query($sql);
}
// Call this one time
setWiner();
// Call this any time you want to get the winner's data
$winner = getWinner();
A more lazy approach, will be to make the getWinner() function to call setwinner if there is no winner yet :
// Get the winner data
function getWinner()
{
$sql = 'SELECT id, fullname, email, number FROM user winner=1';
$query = mysql_query($sql);
mysql_num_rows($result) == 1) {
$user = mysql_fetc_assoc($query);
} else {
// If there is no winner yet, automatically create one
setWinner();
// Recall the function which should now find a winner
$user = getWinner();
}
return $user;
}
That's up to your context, but on general point of view it's bad practice, because a function which looks like reading data (getSomething) will, under some circumstances, also alter data (call to setWinner().

Implementing facebook-style "unlike" function

I've recently implemented a custom liking and disliking feature for my comics site. I'd like to give users the ability to "Take back" their selection by "unclicking" the like or dislike button.
My function works by:
1) Passing button value (id = 'like' or id = 'dislike') via Jquery to
php script
2) script will first check if an ip exists in the database against
that given comic id... if not it will insert user's IP and current
comic ID... if it does, it originally said "you've already voted"... but now to implement "unliking", I will just have it run a delete query
3) then it will get total current likes for that comic id and
increment.
The way I think it can be done is if the user presses the button again, I basically run the opposite query... delete that user's vote from the table given that comic id... then decrement total likes for that image in the comics table.
So my questions are,
1) Is doing an insert query if they press a button once, then a delete
query if they "deselect" that same choice the best way to implement
this? Couldn't a user spam and overload the database by continuously
pressing the like button, thereby constantly liking and unliking?
Should I just implement some sort of $_SESSION['count'] for that ID?
2) If I'm storing a certain IP... what happens if several uniques
users happen to use the same computer at... let's say a netcafe... it
will always store that user's IP. Is storing against the IP the best
way to go?
Code if you need a reference:
<?php
include 'dbconnect.php';
$site = $_GET['_site'];
$imgid = intval($_GET['_id']);
$input = $_GET['_choice'];
if ($site == "artwork") {
$table = "artwork";
}
else {
$table = "comics";
}
$check = "SELECT ip, tablename, imgid FROM votes WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND tablename = '$table' AND imgid = $imgid";
$result = $mysqli->query($check);
if ($result->num_rows == 0) {
//Insert voter's information into votes table
$sql = "INSERT INTO
votes (ip, tablename, imgid)
VALUES
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)
ON DUPLICATE KEY UPDATE
imgid = VALUES(imgid)";
if (!$mysqli->query($sql)) printf("Error: %s\n", $mysqli->error);
/*while ($row = $result->fetch_assoc()) {
echo "you've inserted: " . $row['ip'] . ", " . $row['tablename'] . ", " . $row['imgid'] . ".";
}*/
$result = $mysqli->query("SELECT like_count, dislike_count FROM $table WHERE id = $imgid");
//put the counts into a list
list($likes, $dislikes) = $result->fetch_array(MYSQLI_NUM);
if ($input == "like") {
$sql = "UPDATE $table SET like_count = like_count + 1 WHERE id = $imgid";
$mysqli->query($sql);
$likes++;
}
else if ($input == "dislike") {
$sql = "UPDATE $table SET dislike_count = dislike_count + 1 WHERE id = $imgid";
$mysqli->query($sql);
$dislikes++;
}
}
else { //"unlike" their previous like for that given image id
$sql = "DELETE FROM
votes
WHERE (ip, tablename, imgid) =
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)";
if (!$mysqli->query($sql)) printf("Error: %s\n", $mysqli->error);
$result = $mysqli->query("SELECT like_count, dislike_count FROM $table WHERE id = $imgid");
//put the counts into a list
list($likes, $dislikes) = $result->fetch_array(MYSQLI_NUM);
if ($input == "like") { //remove like
$sql = "UPDATE $table SET like_count = like_count - 1 WHERE id = $imgid";
$mysqli->query($sql);
$likes--;
}
else if ($input == "dislike") {
$sql = "UPDATE $table SET dislike_count = dislike_count - 1 WHERE id = $imgid";
$mysqli->query($sql);
$dislikes--;
}
}
echo "Likes: " . $likes . ", Dislikes: " . $dislikes;
mysqli_close($mysqli);
?>
1) I would say yes, use a count feature to limit the number of attempts they can hit the button in succession. Probably wouldn't have much trouble unless they hit really high numbers, I believe a simple loop would do fine.
2) I would not store just the IP. I would try and use something more than just the IP as an Identifier, like the IP and the session cookie - that way it's unique. However on the look back to the server you would have to parse the entry from the db. Or perhaps the mac address. I'm not sure if you have access to that or not. How can I get the MAC and the IP address of a connected client in PHP?
I'm sure there's another way but conceptually that's how I see it working.

Updating records If ipAddress and playerName match

At the moment im sending scores and data to my database from my flash game, though every level completed is a new record.
feilds are set out like l1Score,l2Score,l3Score
im trying to figure out how to update records if the field ipAddress and playerName match the current $varibles.
UPDATE highscores SET l2Score = '$l2Score' WHERE ipAddress = "$ipAddress" && playerName = '$playerName'
I was thinking somthing along these lines, but could someone point me in the right direction please!
First you want to perform a query to check if there is already a score in place for that user & IP.
$sql = "SELECT * FROM highscores WHERE ipAdress = '$ipAdress' AND playerName = '$playerName'";
$result = mysql_query($sql, $con);
$row = mysql_fetch_assoc($result);
Now, if $row is empty then you want to insert a new record, else you want to update a previous record.
if($row == "")
{
$query = "INSERT INTO highscores (l2score, ipAdress, playerName) VALUES ('$l2score', '$ipAdress', '$playerName'";
} else {
$query = "UPDATE highscores SET l2Score = '$l2Score' WHERE ipAdress = '$ipAdress' AND playerName = '$playerName'";
You may need to edit this to fit with the specific query that you need.

Categories