I need to create a counter for member section (count the number of times a user logged).
I have the following script (counter.php):
<?php
$conn = mysql_connect("localhost", "myuser", "mypass");
mysql_select_db("test");
$sql = "SELECT views FROM members WHERE mid = " . $_GET['mid'];
$result = mysql_query($sql);
if (!$result)
{
mail(ADMIN, 'Cannot Get: ' . mysql_error(), mysql_error());
}
while ($row = mysql_fetch_assoc($result))
{
$count = $row['views']++;
}
$query = "UPDATE members SET views = '$count' WHERE mid = " . $_GET['mid'];
mysql_query($query);
mysql_close($conn);
// show the logo using header() and readfile(); // that part work
?>
DB:
CREATE TABLE `members` (
`mid` int(11) NOT NULL AUTO_INCREMENT,
`views` int(11) DEFAULT '0',
/* etc...*/
PRIMARY KEY (`mid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Now, what I do in my .htaccess file is:
RewriteEngine On
RewriteRule ^img/logo([0-9]+).jpg$ /counter.php?mid=$1 [L]
but for some reason my counter does not count correctly. What am I missing?
You could probably just simplify it and do the following:
$query = "UPDATE members SET views = views + 1 WHERE mid = " . $_GET['mid'];
mysql_query($query);
if (mysql_affected_rows() == 0) {
mail(ADMIN, 'Cannot Get: ' . mysql_error(), mysql_error());
}
mysql_close($conn);
No need to do initial check.
use this
$count = $row['views'] + 1;
or
$count = ++$row['views'];
or
$query = "UPDATE members SET views = views + 1 WHERE mid = " . $_GET['mid'];
syntax:
$x = 1;
$count = $x++;
// $count = 1
$x = 1;
$count = ++$x;
// $count = 2
The problem is in the line
$count = $row['views']++;
This actually says:
- Assign the value of view to $count
- Increment views.
But you want:
$count = ++$row['views'];
Which says:
- Increment views.
- Assign the (incremented) value of view to $count
A subtle difference. :~)
Related
I have a 2-column table which I create like this (each user has a table for himself):
$sql = "CREATE TABLE $user_name (
driver TINYTEXT NOT NULL,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
I have (manually, using phpMyAdmin) inserted data into one such a table. reg_date was set at current time and some random string (numerical, say 01234) was inserted.
I try accessing the rows like this:
$mysql_qry2 = "SELECT * FROM $username";
$result2 = mysqli_query($conn, $mysql_qry2);
$ans = "";
if(mysqli_num_rows($result2) > 0) {
while ($row = mysqli_fetch_assoc($result2)) {
$ans = $ans . $row["driver"];
$ans = $ans . " ";
$x = $row["driver"];
echo "$x";
echo "a";
}
$ans = $ans . "asd";
echo "$ans";
} else {
echo "b";
}
edit: after fixing my mistaken variable name, the "SELECT *" query is returning zero rows despite 3 rows of data being there.
You checked count of wrong variable mysqli_num_rows($result) > 0.
$mysql_qry2 = "SELECT * FROM $username";
$result2 = mysqli_query($conn, $mysql_qry2);
$ans = "";
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
$ans = $ans . $row["driver"];
echo "$ans";
echo "a";
}
} else {
echo "b";
}
Hello I want to run two queries in this code. The first delets a row in the mysql table and the second reorders the id value to the right sequence.
if(isset($_POST["image_id"]))
{
$file_path = 'files/' . $_POST["image_name"];
if(unlink($file_path))
{
$count= 0;
$count++;
$query1 = "DELETE FROM tbl_image WHERE image_id = '".$_POST["image_id"]."'";
$query2 = "UPDATE 'tbl_image' SET 'image_id' = '$count' " ;
$statement = $connect->prepare($query1, $query2);
$statement->execute();
}
}
I'm trying to figure how to call a query once.
I have 6 different variables for images, title and desc.
In this code, I need to know how to loop for id from 0 to 6.
$date = new DateTime("NOW");
$image1 = 'SSSS';
$title1 = 'AAAA';
$desc1 = 'BBBB';
$image2 = 'RRRR';
$title2 = 'GGGG';
$desc2 = 'VVVV';
/// 4 vars later....
$id = 6;
$get = $this->db->queryRow("UPDATE `featured` SET `image` = '{$image.$id}', `title` = '{$title.$id}', `desc` = '{$desc.$id}', `date` = '{$date->format('Y-m-d H:i:s')}' WHERE id = '{$id}'");
return(object) $get;
To build a collection of Querys use the multi_query function.
Loop to build your Query string to pass to the db and concatenated by a semicolon.
<?php
for($i=0;$i <= $maxquerys;$i++){
$query = "UPDATE `featured` SET `image` = '".$image.$id."', `title` = ".$title.$id."', `desc` = '".$desc.$id."', `date` = '".$date->format('Y-m-d H:i:s')."' WHERE id = '".$id."';"
}
/* execute multi query */
if ($mysqli->multi_query($query)) {
while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
you may check also the result by
echo $mysqli->affected_rows;
?>
I have tried to use a simple $query model and it works fine.
Create a valid Query string to pass to the db
<?php
$query = "UPDATE `featured` SET `image` = '".$image.$id."', `title` = ".$title.$id."', `desc` = '".$desc.$id}."', `date` = '".$date->format('Y-m-d H:i:s')."' WHERE id = '".$id."';"
$result=$mysqli->query($query);
// Verify results
if(!$result) {
$ErrMessage = "ErrSqlQuery:" . $mysqli->error . "\n";
$mysqli->close();
die($ErrMessage);
}
you can check also the result by
echo $mysqli->affected_rows;
?>
$query_build = "";
foreach($arr as $$image){
$query_build .= "UPDATE `featured` SET `image` = '{$image.$id}', `title` = '{$title.$id}', `desc` = '{$desc.$id}', `date` = '{$date->format('Y-m-d H:i:s')}' WHERE id = '{$id}';";
}
$get = $this->db->queryRow($query_build);
Accumulate all the queries and execute all at once.
I'm working on a project where I have to show the leaderboard of players. But when wrote the below code, It shows the ranks with 2, 4, 6, 8, ... But not the odd numbered ranks. Can anyone tell me "What's wrong in this ?"
$query1_string = "CREATE VIEW Leaderboard AS SELECT Name, Points, PhoneNo
FROM user ORDER BY Points DESC";
$query2_string = "set #rank = 0";
$query3_string = "SELECT #rank := #rank + 1 as Rank, Name, Points
FROM Leaderboard";
$query5_string = "DROP VIEW Leaderboard";
// Doing the queries
$query1 = mysqli_query($con, $query1_string) or die(mysqli_error($con));
$query2 = mysqli_query($con, $query2_string) or die(mysqli_error($con));
$query3 = mysqli_query($con, $query3_string) or die(mysqli_error($con));
// Initializing the count
$count = 0;
//Making an array of strings including Rank, Name and Points of the Top 5 Players
while (($count < 5) && (mysqli_fetch_array($query3, MYSQL_NUM))) {
$row = mysqli_fetch_array($query3, MYSQL_NUM);
$results[$count] = $row[0] . " " . $row[1] . " " . $row[2];
$count++;
}
// Dropping the view.
$end_query = mysqli_query($con, $query5_string) or die(mysqli_error($con));
//Returning the array
$leader = implode("\n", $results);
echo $leader;
You are executing the query3 two times and displying the data retrieved from second execution
while (($count < 5) && (mysqli_fetch_array($query3, MYSQL_NUM))) {
$row = mysqli_fetch_array($query3, MYSQL_NUM);
I wrote a code that lets the user vote for one out of the two options and the score is calculated using a modified Elo rating system. However, digits to the right of the decimal point are ignored when I vote for either of the options. I added the floatval function but it didn't help.
$query = "SELECT pic,score,id FROM nfl
JOIN (SELECT r1.random_id
FROM nfl_map AS r1
JOIN (SELECT (RAND() *
(SELECT MAX(row_id)
FROM nfl_map)) AS row_id)
AS r2
WHERE r1.row_id >= r2.row_id
ORDER BY r1.row_id ASC
LIMIT 1) as rows ON (id = random_id)";
$query_2 = "SELECT pic,score,id FROM nfl
JOIN (SELECT r1.random_id
FROM nfl_map AS r1
JOIN (SELECT (RAND() *
(SELECT MAX(row_id)
FROM nfl_map)) AS row_id)
AS r2
WHERE r1.row_id >= r2.row_id
ORDER BY r1.row_id ASC
LIMIT 1) as rows ON (id = random_id)";
$res_2 = $mysqli->query($query_2);
if (!$res_2) die ("Result display failed: " . $mysqli->errno . " - " . $mysqli->error);
$pic_2 = $res_2->fetch_assoc();
$id_2 = $res_2->fetch_assoc();
$score_2 = $res_2->fetch_assoc();
$res_1 = $mysqli->query($query);
if (!$res_1) die ("Result display failed: " . $mysqli->errno . " - " . $mysqli->error);
$pic_1 = $res_1->fetch_assoc();
$id_1 = $res_1->fetch_assoc();
$score_1 = $res_1->fetch_assoc();
$Ra = $score_1;
$Rb = $score_2;
$calc_pow_1 = (($Rb - $Ra) / 400);
$calc_pow_2 = (($Ra - $Rb) / 400);
$float_calc_pow_1 = floatval($calc_pow_1);
$float_calc_pow_2 = floatval($calc_pow_2);
$Ea = 1 / (1 + pow(10,$float_calc_pow_1));
$Eb = 1 / (1 + pow(10,$float_calc_pow_2));
$float_Ea = floatval($Ea);
$float_Eb = floatval($Eb);
// if user votes for picture no. 1
if (isset($_POST['vote_1']) && isset($_POST['id']) && isset($_POST['score']))
{
$id = $_POST['id'];
/* $score = $_POST['score'];
$pic = $_POST['pic']; */
//$mod = 2 * $Eb;
$K = 4;
$float_mod_1 = floatval($K * (1 - $float_Ea));
$query = "UPDATE nfl SET score=?+$float_mod_1 WHERE id=?";
// $score_new = $_POST['score'] + $mod;
$score_new = $_POST['score'] + $float_mod_1;
$stmt = $mysqli->prepare($query);
$stmt->bind_param('di', $_POST['score'], $_POST['id']);
$stmt->execute();
if ($stmt->errno) {
echo "Vote failed: " . $stmt->error();
}
else echo "Vote succeeded! New score of $id_1 is $score_new!";
$stmt->close();
}
// fetch picture no. 2
//
// query to the database
/* $query_2 = "SELECT pic,score,id FROM nfl
JOIN (SELECT r1.random_id
FROM nfl_map AS r1
JOIN (SELECT (RAND() *
(SELECT MAX(row_id)
FROM nfl_map)) AS row_id)
AS r2
WHERE r1.row_id >= r2.row_id
ORDER BY r1.row_id ASC
LIMIT 1) as rows ON (id = random_id)";
$res_2 = $mysqli->query($query_2);
if (!$res_2) die ("Result display failed: " . $mysqli->errno . " - " . $mysqli->error);
$pic_2 = $res_2->fetch_assoc();
$id_2 = $res_2->fetch_assoc();
$score_2 = $res_2->fetch_assoc(); */
// if user votes for picture no. 2
if (isset($_POST['vote_2']) && isset($_POST['id']) && isset($_POST['score']))
{
$id = $_POST['id'];
/* $score = $_POST['score'];
$pic = $_POST['pic']; */
//$mod = 2 * $Ea;
$K = 4;
$float_mod_2 = floatval($K * (1 - $float_Eb));
$query = "UPDATE nfl SET score=?+$float_mod_2 WHERE id=?";
// $score_new = $_POST['score'] + $mod;
$score_new = $_POST['score'] + $float_mod_2;
/* $query = "UPDATE nfl SET score=?+1 WHERE id=?";
$score_new = $_POST['score'] + $mod; */
$stmt = $mysqli->prepare($query);
$stmt->bind_param('di', $_POST['score'], $_POST['id']);
$stmt->execute();
if ($stmt->errno) {
echo "Vote failed: " . $stmt->error();
}
else echo "Vote succeeded! New score of $id_2 is $score_new!";
$stmt->close();
}
Here is the full code, if you need to see it: http://snipt.org/vDhj2
The code handling the situation when the user votes for the second option is pretty much the same (except $Ea changes to $Eb etc.). The 'score' row's properties in MySQL are following:
float(8,3) not null
Thanks.
EDIT: I'm not getting the notice anymore.
I think you simply missed a declaration in your code:
$res_1 = $mysqli->query($query);
if (!$res_1) die ("Result display failed: " . $mysqli->errno . " - " . $mysqli->error);
$pic_1 = $res_1->fetch_assoc();
$id_1 = $res_1->fetch_assoc();
$score_1 = $res_1->fetch_assoc();
$Ra = $score_1;
$Rb = $score_2;
I cannot see $score_2 defined anywhere in the code above where you try to assign it's value to another variable.
Warnings are there for a reason - ignoring them is a bad idea as it will inevitably lead to an error in your code. in this case, you simply need to declare your variable before you assign it (even if it is si,ply $score_2=0; if that is to be the default value, but assign it nonetheless.
Since it's just a notice, does it matter? If so, what should I change
in my code?
incorrectly written code that throws an error needs to be fixed.
you cannot assign $Rb = $score_2 before you create the $score_2 variable -- that is an error. put them in the right order to solve that problem
Getting a notice in PHP isn't an ERROR obviously, it's just ugly and can burden your load...
the notice you're getting means that you're using a non-set variable, doing a var_dump(isset($score_2)) will result in bool(false), meaning that it wasn't set.
PHP is a dynamically typed language, meaning that you don't have to declare variables prior to using them, however - it's a good practise if you do, to avoid such notices which could result in errors you simply need to declare the variable prior to using it.
are you expecting a number?
initialize it so
$score_2 = 0;
or
$score_2 = null;
depends on your needs, if you fill it with null, don't forget to allow in mysql NULL values...
Okay I found it. It was a stupid mistake with fetch_assoc() etc. Here is the revised code: http://snipt.org/vEaj7