PHP update mysqli only works until closing browser - php

I have a question about the update function in mysqli.
For school, I'm trying to create a click counter for my website which counts how many times a user has visited a certain page.
So far I've come up with this:
<?php
/*
* ToDo: Check why number of clicks goes back to two when completely
* refreshing page.
*
*/
include("init.php");
session_start();
//Count variable
$clicks = 0;
//Query for checking if there are any entry's in the database
$query = "SELECT * FROM `beoordelingen`.`clickcounter` WHERE `game_id`={$id}";
$result = $conn->query($query);
//If query returns false
if (!mysqli_num_rows($result)) {
//Create entry in database
$insert = "INSERT INTO `beoordelingen`.`clickcounter` (`ID`, `game_id`, `clicks`) VALUES (NULL, '1', '1');";
$createEntry = $conn->query($insert);
}
//If query returns true
else {
//Setting the number of clicks equal to $clicks
while ($data = $result->fetch_assoc()) {
$clicks = $data['clicks'];
}
//Insert new number into database
$sql="insert into `clickcounter` set `clicks`='{$clicks}', `game_id`='{$id}'
on duplicate key update
`clicks`=`clicks`+1;";
$insertInto = $conn->query($sql);
//Echo current number of clicks
echo $clicks;
}
?>
The actual problem is that my update statement doesn't seem to work properly. If anyone would be able to spot why it doesn't work I'd be very happy.
The database is as following;
Beoordelingen <- Database
clickcounter <- Table which has the following three columns:
1. ID
2. game_id
3. clicks
The scripts does add an entry into the databse with click count 2. So when I reload the page it says 2. And when refreshing it counts up, but doesn't update the table.
Thanks! If anything is unclear please ask me!

Theoretically you should be able to do all of it in one query if game_id is unique.
Given the following table structure the sql query below will insert if the relevant record does not exists and then update if it does.
create table `clickcounter` (
`id` int(10) unsigned not null auto_increment,
`game_id` int(10) unsigned not null default '0',
`clicks` int(10) unsigned not null default '0',
primary key (`id`),
unique index `game_id` (`game_id`)
)
engine=innodb;
The trick is setting the indices on your table correctly ~ initially you don't know the value of the ID and I would guess that is an auto increment primary key? So, set a unique key on game_id...I hope it helps!
/* Could even change `clicks`='{$clicks}' to `clicks`=1 in initial insert */
$sql="insert into `clickcounter` set `clicks`='{$clicks}', `game_id`='{$id}'
on duplicate key update
`clicks`=`clicks`+1;";
<?php
include("init.php");
session_start();
/* Where / how is "$id" defined? */
/* insert new record / update existing */
$sql="insert into `clickcounter` set `clicks`=1, `game_id`='{$id}'
on duplicate key update
`clicks`=`clicks`+1;";
$result = $conn->query( $sql );
/* retrieve the number of clicks */
$sql="select `clicks` from `clickcounter` where `game_id`='{$id}';";
$result = $conn->query( $sql );
while( $rs=$result->fetch_object() ) $clicks=intval( $rs->clicks );
echo 'Total clicks: '.$clicks;
?>

Related

Database INSERT INTO error

I was trying to find out what was wrong with my code.
This is the error I'm recieving
"Cannot add or update a child row: a foreign key constraint fails "
This is my code
<?php
$sql = "INSERT INTO stasjon (navn) VALUES ('skogen', 'voksenlia') ";
$resultat = $kobling->query ($sql);
$sql ="SELECT * FROM stasjon WHERE navn = ('skogen')";
$resultat = $kobling->query ($sql);
while ($rad = $resultat->fetch_assoc()) {
$stasjon_id = $rad['stasjon_id'];
}
$sql = "INSERT INTO linjestasjon (linje_nr, stasjon_id) VALUES ('1','$stasjon_id')";
$resultat = $kobling->query ($sql);
if($kobling->query($sql)) {
echo "Spoerringen $sql ble gjennomfoert.";
} else {
echo "Noe gikk galt med spoerringen $sql ($kobling->error).";
?>
Some of it is in Norwegian because That's the language of the database I'm making. I was trying to add values to two different tables (that had stasjon_id as a foreign key) Thanks in advance
Foreign Key constraints checks in the value that you are inserting or updating to a particular filed exists in some other filed of another table. Suppose I have 2 tables as follows
CREATE TABLE TableA
(
SeqNo INT PRIMARY KEY,
Name VARCHAR(500
)
CREATE TABLE TableB
(
SeqNo INT NULL FOREIGN KEY REFERENCES TableA(SeqNo),
Name VARCHAR(50)
)
So when you insert a new record to the Tableb.SeqNo filed, The value should either be NULL or some value that exists in the TableA.SeqNo.
So Before inserting the values make sure that you are inserting the value that satisfy your foreign key constraint

prevent duplicate records in mysql table

Im creating a website for booking activities. I have 3 centres. The customer is cant book the same activity twice neither in a different centre. Im using a table in mysql which i store the infos provided by the costumers. Is there any way to filter or to check in my php code if a customer has already booked the same activity more than one time and echo an error msg?
my table(and the info im asking) contains these columns:
ID(Primary)
FirstName
LastName
Email
ContactNumber
ClassName
Week
Intensity
CentreName
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
When you create the table add the unique attribute to the fields you want to prevent, something like this
CREATE TABLE Persons
(
P_Id INT NOT NULL AUTO_INCREMENT,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
UNIQUE (P_Id)
)
If you already have created the table just edit it like this
ALTER TABLE Persons
ADD UNIQUE (P_Id)
Hope this helps you; If you do not have a unique id i believe this will suit you best on what you need; Note that this is not the full code; You need to add some to other information to fit in your question;
// Checks if the value already exist on the database
$query = SELECT EXISTS(SELECT column_name FROM table_name WHERE
condition LIMIT 1)
// If condition is not met it will proceed with save
if (mysql_num_rows(!$query) > 0) {
echo "Activity Booked";
} else { // If condition is met it will echo an error message
echo "Unable to booked activity"; }
You need to create a unique (composite) index on the column(s) that you wish to be unique. You can disregard your PK when making your unique index. In your case your sql would look something like:
Alter table yourtablename
add unique index idx_unq(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`);
Then do an INSERT IGNORE INTO instead of an INSERT INTO.
This post may also help you.
"INSERT INTO .. ON DUPLICATE KEY UPDATE" Only inserts new entries rather than replace?
In order to see if record already exist in table you must first "test" to see if that exact record exist in your table. This is to be done before the 'Insert IGNORE Into' in your logic. Using the variables your code would look something like this:
$testcount = "Select count(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`)
from yourtablename
where
(LastName = '$LastName' AND FirstName= '$FirstName' AND Email= '$EMAIL' AND ContactNumber= '$ContactNumber' AND ClassName= '$ClassName' AND Week= '$Week' Intensity = '$Intensity' AND CentreName = '$CentreName' )";
This query will give you back (assuming there are no duplicates already in the table) a 0 or a 1 and store it in your $testcount variable. This can then be used to either determine based on the value to insert the record into the table or print a message to end user informing them that it already exist.
I am not sure how you want to structure the php code but the psuedocode would look something like:
If $testcount = 1 then do your insert.
else if $testcount = 0 then echo your message.

PHP/MySQL; For loop to to insert rows only adds one

I'm using a for loop to add a specific number of rows to the table Beds as placeholders. The code doesn't throw any error, but only the last numbered bed appears in the database. I.e.: if you try to add 10 beds, only bed 10 gets added.
Here is the for loop I am using:
$roomName = mysqli_real_escape_string($con, $_POST['roomName']);
$numberBeds = mysqli_real_escape_string($con, $_POST['numberBeds']);
for($x=1; $x <= $numberBeds; $x++) {
$sql = "INSERT INTO Beds (roomName, bedNumber, patientID) VALUES('$roomName','$x', NULL)";
}
And here is the accompanying table:
DROP TABLE IF EXISTS `ChildrensHospital`.`Beds` ;
CREATE TABLE IF NOT EXISTS `ChildrensHospital`.`Beds` (
`roomID` INT(20) NOT NULL AUTO_INCREMENT,
`bedNumber` INT(10) NOT NULL,
`patientID` INT(20) NULL,
PRIMARY KEY (`roomID`, `bedNumber`),
INDEX `fk_Beds_PatientPersonalInformation1_idx` (`patientID` ASC),
CONSTRAINT `fk_Beds_PatientPersonalInformation1`
FOREIGN KEY (`patientID`)
REFERENCES `ChildrensHospital`.`PatientPersonalInformation` (`patientID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
I'm not sure if it's a syntax error in my PHP code, or something about the table itself.
Any help would be appreciated.
The problem with your code is that you are not executing your query. Try it like this:
for($x=1; $x <= $numberBeds; $x++){
$sql = "INSERT INTO Beds (roomName, bedNumber, patientID) VALUES('$roomName','$x', NULL)";
mysqli_query($con,$sql);
}
I guess that you are only executing your query after the loop and thus, of course only the last query gets executed instead of each.

Update counter using php and mysql in a session

Problem: I want to connect two tables files and counter according to the paper_id column from files table connecting with the visitors column from counter table.
There are two pages; publicationView.php and profile.php.
When a reader clicks publicationView.php, php code should count the view of the page according to the publication id and only update using session.
When a user visits his profile.php, then he can see his publications in a table with the publications' views relatively.
There are two tables; files where all the publications are and counter where the counter are. I am trying to update using the URI of the publication and the URI is saved in counter table.
Implementation:
The publicationView.php includes
$webpage=htmlspecialchars($_SERVER["REQUEST_URI"]);
$sql = "CREATE TABLE IF NOT EXISTS counter (
id int(4) NOT NULL auto_increment,
webpage varchar(90) NOT NULL,
visitors int(11) NOT NULL default '1',
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1";
mysql_query($sql);
$result=mysql_query("SELECT * FROM counter WHERE webpage='$webpage'");
$num_rows = mysql_num_rows($result);
if ($num_rows == 0){
mysql_query("INSERT INTO counter (id, webpage, visitors)
VALUES ('','$webpage','1')");
}else{
if (!isset($_SESSION['webpage'])){$_SESSION['webpage'] = 0;
mysql_query("UPDATE counter SET visitors=visitors+'1' WHERE webpage='$webpage'");}}
The profile.php includes
The code to echo our the visitors column from counter table.
Change '1' to simply 1 in,
if (!isset($_SESSION['webpage'])){$_SESSION['webpage'] = 0;
mysql_query("UPDATE counter SET visitors=visitors+'1' WHERE webpage='$webpage'");}}
Change it to
if (!isset($_SESSION['webpage'])){$_SESSION['webpage'] = 0;
mysql_query("UPDATE counter SET visitors=visitors+1 WHERE webpage='$webpage'");}}

JQuery & PHP Star Rating simplified

EDIT: The plugin in question is located here.
PHP beginner here using a JQuery Star Rating snippet and have gotten it to work perfectly. My problem is that it is currently configured to count and display the average of many ratings (for public applications). I'm trying to simplify the plugin so that it allows one to set a personal rating (as if rating your own songs in iTunes). The user may update their rating, but no partial stars would ever exist. I've broken the plugin many times trying to get it working, but to no avail. The mysql database exists as follows:
CREATE TABLE IF NOT EXISTS `pd_total_vote` (
`id` int(11) NOT NULL auto_increment,
`desc` varchar(50) NOT NULL,
`counter` int(8) NOT NULL default '0',
`value` int(8) NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
If I can get it working the way I imagine, I wouldn't require both the counter and value columns, simply a single INT column that holds a value between 1 and 5. Currently counter accumulates the number of votes, while value aggregates the ratings. The stars are then displayed using (value/counter)*20 (as a percentage). The PHP is below (original):
<?php
// connect to database
$dbh=mysql_connect ("localhost", "user", "pass") or die ('Cannot connect to the database');
mysql_select_db ("thenally_pd",$dbh);
if($_GET['do']=='rate'){
rate($_GET['id']);
}else if($_GET['do']=='getrate'){
// get rating
getRating($_GET['id']);
}
// get data from table
function fetchStar(){
$sql = "select * from `pd_total_vote`";
$result=#mysql_query($sql);
while($rs = #mysql_fetch_array($result,MYSQL_ASSOC)){
$arr_data[] = $rs;
}
return $arr_data;
}
// function to retrieve
function getRating($id){
$sql= "select * from `pd_total_vote` where id='".$id."' ";
$result=#mysql_query($sql);
$rs=#mysql_fetch_array($result);
// set width of star
$rating = (#round($rs[value] / $rs[counter],1)) * 20;
echo $rating;
}
// function to set rating
function rate($id){
$text = strip_tags($_GET['rating']);
$update = "update `pd_total_vote` set counter = counter + 1, value = value + ".$_GET['rating']." where id='".$id."' ";
$result = #mysql_query($update);
}
?>
Thanks for a point in the right direction,
Mike
I am unsure as I have no access to the rating system you are using yet just glancing at what you have I guess you could keep the counter set to 1 (if removing it breaks the jQuery Rating System) and have the value updated by the person so when you fetch it they only see their value (make sure value can't go above 5). That way if the value is set to 5 then it will show 5 because it isn't finding other ratings.... (based on my understanding) You will also have to add a user id so you know which persons rating to fetch (since you want it personal). This depends on how dependent the application is a specific database design.

Categories