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.
Related
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`);
This is what i am trying right now but no luck
$bid = $next - 2;//This subtracts 2 from the number, this number is also auto generated
$preid = $bid;
$query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$query) or die(mysqli_error($conn));
while(mysqli_num_rows($sql) !=0) {
$select_query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
--$preid;
}
whats suppose to happen is that if a record does not exist it subtracts 1 from preid and runs the query again with the new preid and keeps happening until a record it found but cant figure out how to do it.
I am assuming that you are constantly checking database for new values. However, on a large scale application thi is an highly inefficient way to constantly ping the database.
You have made a variable $preid but you are not using it anywhere.
This is how i would do it if i were to go according to your way
$bid = $next - 2;//This subtracts 2 from the number, this number is also auto generated
$preid = $bid;
$query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$query) or die(mysqli_error($conn));
while(mysqli_num_rows($sql) !=0 || !$preid) { //notice here i added the condition for preid.
$select_query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
--$preid;
}
now what happens is that the loop will run as long as either of the two condition stays true ie either a row is returned from the database or it will keep searching until preid is not 0.
If you want to test for an empty set, your while should run while mysqli_num_rows == 0
while(mysqli_num_rows($sql) == 0) {
$select_query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
$preid--;
}
As #DarkBee has mentionend in his comment, this code is highly vulnerable for an infinite loop which will take down your script, as soon as there are no entries for anything.
I am using if else condition with foreach loop to check and insert new tags.
but both the conditions(if and alse) are being applied at the same time irrespective of wether the mysql found id is equal or not equal to the foreach posted ID. Plz help
$new_tags = $_POST['new_tags']; //forget the mysl security for the time being
foreach ($new_tags as $fnew_tags)
{
$sqlq = mysqli_query($db3->connection, "select * from o4_tags limit 1");
while($rowq = mysqli_fetch_array($sqlq)) {
$id = $rowq['id'];
if($id == $fnew_tags) { //if ID of the tag is matched then do not insert the new tags but only add the user refrence to that ID
mysqli_query($db3->connection, "insert into user_interests(uid,tag_name,exp_tags) values('$session->userid','$fnew_tags','1')");
}
else
{ //if ID of the tag is not matched then insert the new tags as well as add the user refrence to that ID
$r = mysqli_query($db3->connection, "insert into o4_tags(tag_name,ug_tags,exp_tags) values('$fnew_tags','1','1')");
$mid_ne = mysqli_insert_id($db3->connection);
mysqli_query($db3->connection, "insert into user_interests(uid,tag_name,exp_tags) values('$session->userid','$mid_ne','1')");
}
}
}
i think you are inserting
$r = mysqli_query($db3->connection, "insert into o4_tags(tag_name,ug_tags,exp_tags)
values('$fnew_tags','1','1')");$mid_ne = mysqli_insert_id($db3->connection);
and then you are using while($rowq = mysqli_fetch_array($sqlq))
which now has records you just inserted therefore your if is executed
I'm pretty sure the select query below will always return the same record.
$sqlq = mysqli_query($db3->connection, "select * from o4_tags limit 1");
I think most of the time it will goes to the else, which execute the 2 insert.
Shouldn't you write the query like below?
select * from o4_tags where id = $fnew_tags limit 1
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.
What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)