I know this question has been answered over a million times, but I'm very new to the whole programming scene and I just can't get it to work. Sorry, I hope you can help me!
HTML:
<div class="the_score">+76</div>
<div id="increment_value">Like</div>
I have a MySQL connection and I can fetch the data, but I want the score to update with +1 when someone clicks the Like div. I have a table "websites" with row "WebScore" that has the function int(10) (?? I hope that is correct).
I use this to fetch the data and show it on my website:
$r = rand(2,3);
$sql = "SELECT * FROM websites WHERE ID = $r";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
I presume you have a column, not a row, called WebScore.
You need the query
UPDATE websites SET WebScore = WebScore + 1 WHERE ID = $r
As you can see, it finds the right row of your table and updates the value of the WebScore column.
This sort of things can only be done from a PHP program. It can't be done directly from a Javascript method invoked within a web browser. So, if you want to react to a user click, you'll need to post a form or invoke an Ajax style call to a php endpoint. How to do that is the province of another question.
Keep plugging away; you'll figure out this database stuff.
Related
I have two pages. One is a form that I use to simply input data that will be sent to my database and the second page that actually takes the data inputted into the form and sends it to the database and is supposed to display the information that I've just added.
Everything works fine, however I'm struggling with the query slightly. What I need it to do is display all the information for the last data inputted to the database.
The query I currently have just displays the data with the highest ID:
$sql = "SELECT * FROM Results ORDER BY ID DESC LIMIT 1";
So as an example I would be left with the following information after completing my form:
Success! Data being saved:
ID = 900 Amount = 206 Date = 2016-12-26
This is obviously just showing the data with the highest ID, but since the ID and all the data fluctuates, I need it to just show the data that has just been inputted.
I came accross this: Query to select newly added records only. But I don't believe this soultion to be viable as the database is external and I don't want to be creating new tables.
I was thinking that it might be possible to assign a hidden value to each newly added record via the query. e.g. New 1, New 2, New 3 etc. Then printing the latest record for New. However, I couldn't find anything on how to do this.
Any help would be greatly appreciated!
You must use this method to have very correct value:
Input form must send to another file that do inserting (we call it here insert.php)
insert.php must insert the data after validation and after that you can fetch the last ID number from database. Depending on the method you are working with it can be different. for example if you are using PDO you can get it by PDO::lastInsertId
after getting the ID you need to forward it to the viewing or editing page. for example view.php?id=LastInsertId. This forward have some reasons:
Codes can be cleaner.
We prevent refresh and resend inserting. for example if you do inserting inside view.php and user hit F5 to refresh the page, The insertion happening again.
This is the whole idea. you can use this method for only one page:
page.php?do=new
page.php?do=insert
forward to the page.php?do=view&id=lastInsertID
why you trying to get just inputted data from database? you can do it using HTTP POST/GET method easily.just send data as parameters and show them in second page.
If you already have the data you are inserting, you don't need to run a query to get it back from the database again, you could just ensure that the query was successful and display the data directly. Anyways:
You can get the insert ID from the last insert using the MySQLi object. For example:
$sql = "<your insert statement>"
$conn->query($sql);
$last_id = $conn->insert_id; //Id of the row you just inserted
$sql = "SELECT * FROM Results WHERE id=$last_id";
This is assuming you do the insert in the same page that you display the result.
I am working on a project where only title of posts are shown on main page and on clicking the title, full post is loaded on another page posts.php code for this is:
<?php echo $row['title']; ?>
Now to count post views I have a column hits in my posts table ,initially value of hits is set to 0 and whenever a post is opened value of hits is increased by 1, for this my code is in posts.php
$id = $_GET['postId'];
$sql = "UPDATE posts SET hits = hits + 1 WHERE post_id = $id";
But this is not a good practice for tracking post views as views increase whenever page is refreshed. I want a clean system to track post views where, for every distinct user or visitor views increase by one irrespective of fact how many times the same user/visitor views same post (as in stackoverflow). Like tracking them by their IP address or something else, just an idea (how these guys do it) or how the stuff works would be enough to let me start my work.
You cannot solve your problem so simply. Your problem is counting unique users who view a page (with, perhaps a time component). You have several problems, as described in the comments. The first is determining what you are counting. For a prototype, IP address is good as anything else for getting started. However, it has many short-comings, and you will need to think hard about identifying a "visitor".
There is a way to solve your problem in SQL, sort of efficiently. But, it requires an additional table at the level of post/visitor. It will have one row per combination, and then you will need to count from there. To quickly get the unique counts, you then need an insert trigger on that table.
Here is a sketch of the code:
create unique index unq_postvisitors_post_visitor on postvisitors(postid, visitorid);
insert into PostVisitors (postid, visitorid)
select $postid, $visitorid
on duplicate key update set counter = counter + 1;
delimiter $$
create trigger trig_PostVisitors
after insert on PostVisitors
begin
update posts
set numvisitors = numvisitors + 1
where posts.post_id = new.post_id;
end;$$
delimiter ;
Simplest way I use to solve this problem is through cookies.
Whenever your page is opened, you check if there's set cookie_name cookie through isset($_COOKIE[$cookie_name]).
If isset returns false, you set a cookie through setcookie(cookie_name, value, expire);, maybe setting expire time to 24h (you have to set it in seconds, so 24h is 84600). Also, you trigger your counting systems with a +1 to your visitor counter.
If isset returns true, do nothing.
PHP Cookies Refs
Try this It'll Work
$refreshed = $_SERVER['HTTP_CACHE_CONTROL'];
if ($refreshed == 'max-age=0'){
$sql = "UPDATE posts SET hits = hits + 1 WHERE post_id = $id";
}
Try this script on the page $_SERVER['HTTP_CACHE_CONTROL'] get place when page is refreshed
I have 1 HTML document (it is .php, but I'll refer to it as HTML doc) with 3 different fill-in-forms which each has their own PHP script for inserting the data into a database. Each form has its own script and its own table in the database.
I need an ID or username I can give the user on the first form's submission, and then store the ID/username variable and insert it into form 2 and in form 3. So what I need is to have a variable pass from one script to two other scripts.
I tried giving a ID/username in the first script, then in the second script I just collect it via SQL from the table. It doesn't seem to work.
Script 1: $personID = 'a1';
Script 2:
$today = date("Y/m/d");
$personID = mysql_query("SELECT personID FROM reviewpi WHERE date >= '$today' ");
Please help?
For those who would like to know how I did it, here is what I did.
In the first scripts I added
session_start();
$_SESSION['personID'] = 'a1b2c3';
and in the 2nd and 3rd script I added
session_start();
$personID = $_SESSION['personID'];
then in my SQL insert statement on each script page (even script1)
$mysqli->query("INSERT into reviewdc ( personID ) VALUES ( '{$_SESSION['personID']}' )" );
My question was probably a stupid and answered question for some of you, but I couldn't find any research on how exactly to do it, and I tried most of the solutions given on other posts, none of them worked.
Thanks for those who helped.
Your query tries to get the ID, based on today's date.
That is not a good approach at all, what if you had multiple persons that day?
Since you are just trying to carry the id over from page to page, a session would be the right tool.
Set the session:
session_start();
$_SESSION['personID'] = 'a1';
Get the session:
session_start();
$personID = $_SESSION['personID'];
If you find your self needing to get the data of that person.
Simply retrieve the ID and query your DB again.
SELECT *
FROM reviewpi
WHERE personID = ?
Please note:
You need to stop using mysql, it's deprecated
Use mysqli or PDO(recommended)
Use prepared statement to avoid SQL injection attacks
For my iPhone web app I have created a database in php MyAdmin, it contains two tables (bookings, waiters and allocations) the I wish to view the bookings within a table in HTML where i can allocate a waiter to that booking. Any tips on how this would be done, any help will be appreciated as this is my first contact with web app development and MyAdmin. Thanks!
Mysql work with autoincrement id. You will have an id after of an insertion. You can to create a table only to id's and after to use it in the insertion of the waiter.
First you will need to get the data from the table via MySQL
$sql = "SELECT * FROM table_name";
$result = mysql_query($sql);
Then you would loop through the result
while($row = mysql_fetch_assoc($result)){
extract($row);
}
Then you can do as you wish with the returned data...
You really need to give us a little more... What have you got so far?
Another question which has me perplexed:
I have a table which enables users to enter as many rows as they like based on their userid and unique id (auto incremental).
I need to be able to get this information from mysql and place the previously entered information into the fields on the web application (they may need to be edited before confirming that they're correct).
I store the total number of records for that user so far in one variable, and the total number of records for all users in another variable.
The question is: how do I get the range of ids for the records the user has already enterered.
Example: User 1 has 2 records in the database and there is 7 in total (5 by another user). How would I get the unique IDs of the 2 records that already exist?
Thanks for any suggestions you may have!
I'm not entirely sure what you mean, so this may or may not be helpful.
This SQL should give you the record ids:
SELECT id FROM tableofuserrows WHERE userid = [User Id]
You can then fetch this from the database with PHP, e.g.
$q = mysql_query('SELECT id FROM tableofuserrows WHERE userid = ' . (int) $_GET['userid']) or die(mysql_error());
$result = array();
while ($row = mysql_fetch_assoc($q)) {
$result[] = $row['id'];
}
mysql_free_result($q);
echo json_encode($result);
So if you wanted to fetch these IDs from the browser using jQuery:
$.getJSON("http://url", { userid: 3 }, //set userid properly
function(data){
$.each(data, function(i,id){
//do something with the recordid
alert(id);
});
}
);
Do you have to do this dynamically using jquery or can you load the fields in the web form with the rest of the page using php ?
Either way, you're going to need to query the database table for all rows where userid = a certain user. Once you get these results, you'll need to create a page you can call and get results from using jquery if you're going that route.
Someone just posted what I'm saying with code examples :-)
I decided to use MIN(id) in the select statement, counting how many rows there are and then populating the form fields accordingly, starting with the min value and adding the counted rows. Works well ;)