I'm trying to count page views on page load, although anytime I load the page 'UPDATE SET views = views + 1' is actually adding 2. I've got my code below, if any one has any suggestions that'd be awesome.
// Create database connection
$db = new mysqli($db[host], $db[user], $db[pass], $db[data]);
// Display database connection error (if applicable)
if (mysqli_connect_errno()){
printf("Connect failed: %s\n", mysqli_connect_errno());
exit();
}
// Define Visitor Variables
$visitor[ip] = $_SERVER['REMOTE_ADDR']?:($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['HTTP_CLIENT_IP']);
// Checks database to see if ip exists in logs
$check[ip] = $db->query("SELECT ip FROM admin_views WHERE ip = '$visitor[ip]'");
// If ip is found in database, update page views counter if it's not found, create a record for it
if ($check[ip]->num_rows == 1){
$db->query("UPDATE admin_views SET views = views +1 WHERE ip = '$visitor[ip]'");
} else {
$db->query("INSERT INTO admin_views VALUES('NULL', '$visitor[ip]')");
echo "not found";
}
// Count the number of views
$count_views = "SELECT SUM(views) AS countViews FROM admin_views";
if ($result = $db->query($count_views)) {
while ($row = $result->fetch_assoc()) {
$views = $row['countViews'];
}
$result->free();
}
// Count unique page views
$count_unique_views = "SELECT id FROM admin_views ORDER BY id DESC LIMIT 1";
if ($result = $db->query($count_unique_views)) {
while ($row = $result->fetch_assoc()) {
$unique_views = $row['id'];
}
$result->free();
}
// Close database connection
$db->close();
Related
How to update a status from database if status is empty in using php? I have this condition in php. I have this if condition that decides if $getstatus is empty it will update from database to Avail. I tried refreshing the page after querying the database. But it will not update in database. Is there anyway to update this without using form submit in php?
<?php
session_start();
include "includes/connection.php";
// Display all parking slots
$sql = $connection->prepare('SELECT * FROM parkingslot where parkingslotid = 1');
$sql->execute(); // execute query
$result = $sql->get_result(); // fetch result
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getstatus = $row["status"];
echo $getstatus;
}
}
if (empty($getstatus)) {
$sql = $connection->prepare("UPDATE parkingslot SET status = 'Avail' where parkingslotid = 1 ");
}
?>
Codes in connection for connecting to database
connection.php
<?php
$server = "localhost";
$username = "root";
$password = "";
// create connection
$connection = mysqli_connect($server,$username,$password);
// check connection
if(!$connection)
{
die("No connection found." . mysqli_connect_error());
}
else {
// select a database
$select_db = mysqli_select_db($connection,'smartparkingsystem');
if(!$select_db)
{
$sql = 'CREATE DATABASE sample';
// create database if no db found
if(mysqli_query($connection,$sql)) {
echo "Database Created";
}
else {
echo "Database not found" . mysqli_connect_error() . '\n';
}
}
else {
// Database already existed
// do nothing...
}
}
?>
If I understand your goal of: For row(s) whereparkingslotid=1 - Update status to 'Avail' but only if status is not currently set, this might help:
<?php
session_start();
include "includes/connection.php";
$connection->prepare("UPDATE `parkingslot` SET `status`=? WHERE `parkingslotid`=? AND (`status` IS NULL OR `status`=?)");
$connection->bind_param("sis", $status, $parkingslotid, $empty_str);
$status = 'Avail';
$parkingslotid = 1;
$empty_str = '';
$connection->execute();
echo $connection->affected_rows.' rows affected';
$connection->close();
?>
This saves a bit of processing by not checking with PHP first.
You can use this query:
"UPDATE parkingslot SET status = 'Avail' where status IS NULL OR status = '' "
Edited:
#lumonald gave the right anwser in the comment. You're not executing your second SQL statement.
When I run the page with an empty database, it will insert the data correctly. When I run the page again, it displays there is already an ID in the database, but it inserts it anyway. Not sure how or why but I've tried every combination of booleans inside the if statements and cant get it to chooch correctly.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database:
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Ask the database for some sweet, sweet data:
$stmt1 = "SELECT orderID FROM orders";
$result = $mysqli->query($stmt1);
//flag (we want to believe that there are no similar IDS so lets make it true):
$flag = true;
//while we got some data, display that shit
while ($row = $result->fetch_assoc()) {
//asign data to variable:
$rowOrderID = $row['orderID'];
//Does it match? if it does set the flag to false so it doesnt get inserted.
if ($rowOrderID == $orderID) {
echo "Row ID" . $row["orderID"] . " Passed ID: " . $orderID . "<br>";
echo "This order is already in the database" . "<br>";
$flag = false;
}
}
//hand the flag over to who ever needs it
return flag;
}
.
if (checkOrderID($orderID) == true) {
//some mysql insert logic here
}
Why are you making this complicated. just do something like this:
$con=mysqli_connect("localhost","root","","price");
$check_query = mysqli_query($con,"SELECT * FROM orders WHERE orderID = $orderID");
if (mysqli_num_rows($check_query) == 0) {
//mysql insert logic here
}
(Noted of course you are going to have your connection logic as well)
Note: You are using Mysqli in object oriented manner but in this example i have not used object oriented manner of DB connection. The connection variable $con must be passed to mysqli_query() method.
Also... random side note, but it's generally a good idea to have a password for your root mysql user.
Here better and short, but please try to use DB connection globally not inside your mothod and try to use prepared statements. But except those you can use following code.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database: I suggest use global DB connection
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//gets recodrs based on $orderID passed to this method
$stmt1 = "SELECT * FROM orders where orderID=$orderID"; //Try to use prepared statement
$result = $mysqli->query($stmt1);
//Store number of rows found
$row_count = $result->num_rows;
if($row_count>0){
return true;
}
else{
return false;
}
}
I've tried like twenty times and the closest I got was when I put in a variable stored in row 1 of the db and it returned the content the last row in the db. Any clarity would be extremely helpful. Thanks.
// Create connection
$coco = mysqli_connect($server, $user, $pass, $db);
// Check connection
if (!$coco) { die("Connection failed: " . mysqli_connect_error()); }
// Start SQL Query
$grabit = "SELECT title, number FROM the_one WHERE title = 'on' AND (number = 'two' OR number='0')";
$result = mysqli_query($coco, $grabit);
// What I need it to do
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$titleit = $row["title"];
$placeit = $row["number"];
$incoming = 'Help';
if ($titleit[$_REQUEST[$incoming]]){
$message = strip_tags(substr($placeit,0,140));
}
echo $message;
}
} else {
echo "not found";
}
mysqli_close($coco);
Put the input that you want to match into the WHERE clause of the query, rather than selecting everything and then testing it in PHP.
$incoming = mysqli_real_escape_string($coco, $_POST['Help']));
$grabit = "SELECT number FROM the_one WHERE title = '$incoming' AND number IN ('two', '0')";
$result = mysqli_query($coco, $grabit);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['number'];
}
} else {
echo "not found";
}
I think you need to add a break; in that if or I would assume it would go through each row in the database and set message if it matches the conditional. Unless you want the last entry that matches...if not you should debug:
if ($titleit[$_REQUEST[$incoming]]){
// set message
}
and see when it's getting set. That may not be the issue, but it's at least a performance thing and could explain getting the last entry
Have you tried print_r($row) to see the row or adding echos to the if/else to see what path it's taking?
Firstly, Thaks for taking a look at my question.
I have a function that works perfectly for me, and I want to call another function from within that function however I'm getting all kinds of issues.
Here are the functions then I'll explain what I'm needing and what I'm running into.
They are probably very messy, but I'm learning and thought I'd try get fancy then clean it up.
function GetStation($id){
$x_db_host1="localhost"; // Host name
$x_db_username1="xxxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
// SQL Query Setup for Station Name
$sql="SELECT * FROM stations WHERE ID = $id LIMIT 1";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
$retnm = $rows['CallSign'];
}
mysql_close();
echo $retnm;
} // Closes Function
// List Delegates Function!!!!!!!!!!!!!!!!!!!
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_st_name = GetStation($StatNm);
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}
So I output ListDelegates() in a page and it displays a nice table etc.
Within ListDelegates() i use the GetStation() function.
This is because the table ListDelegates() uses contains the station ID number not name so I want GetStation($id) to output the station name
The problem I'm having is it seems GetStation() is outputting all names in the first call of the function so the first row in the table and is not breaking it down into each row and just one at a time :S
Here's what I think (I'm probably wrong) ListDelegates() is not calling GetStation() for each row it's doing it once even though it's in the loop. ??
I have no idea if this should even work at all... I'm just learning researching then trying things.
Please help me so that I can output station name
At the end of GetStation, you need to change
echo $retnm;
to
return $retnm;
You are printing out the name from inside the function GetStation, when you are intending to store it in a variable. What ends up happening, is that the result of GetStation is effectively echo'ed on the screen outside of any table row. Content that is inside a table but not inside a table cell gets collected to the top of a table in a browser. If you want to see what I mean, just view source from your browser after loading the page.
You don't need to connect to the database in each and every function. Usually you do the database connection at the top of your code and use the handle (in PHP the handle is usually optional) throughout your code. I think your problem is because when you call the function each time it makes a new connection and loses the previous data in the query.
My dear first of all you should place your code of connection with local host and database globally. It should be defined only once. you are defining it in both function.
something like this, and as suggested, you should have connection to database established somewhere else
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
//$d_st_name = GetStation($StatNm);
$sql="SELECT * FROM stations WHERE ID = $StatNm LIMIT 1";
while($rows=mysql_fetch_array($result)){
$d_st_name = $rows['CallSign'];
}
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}
I have a nice page including system here is the code for it
if(isset($HTTP_GET_VARS['mod']))
{
$page = $HTTP_GET_VARS['mod'];
}
else
{
$page = 'home';
}
switch($page)
{
case 'home':
require('home.php');
break;
default:
echo('Error: There is no file on this server with that name');
}
}
I am trying to get the case, require from a DB called pages there are 2 fields Name, Link i am trying to get all of the results from the table so it will display the pages
It's not particularly clear from your question, but my reading of it is that you want a way to check any value of $page against a link value in a db table (pages?), without having to write all possible values in to your switch statement,
If my understanding is correct, then the below is a quick-and-dirty function which should let you do this. In a live, heavily-trafficed environment you'd obviously need to build in caching so every page load doesn't hit the db, and strong input validation, neither of which are in the demo below, but this should at least give you an idea of where to go next.
Common library file:
/**
* Given a page name, see if we have an associated
* link in the db.
* If so, return the link value, else false
*/
function getTemplate($page)
{
// Check db to see if we have a link for this page
// On heavy-traffic sites, this should be cached out
$query = sprintf("SELECT link FROM pages WHERE name = '%s'",
mysql_real_escape_string($page));
$result = mysql_query($query, $db_cnx);
// Have we any results?
if (mysql_num_rows($result) > 0)
{
// Assumption: 'name' is unique in the db
$row = mysql_fetch_assoc($result);
return $row['link'];
}
else
{
return false;
}
}
Header.php:
include('common.lib.php');
if(isset($HTTP_GET_VARS['mod']))
{
$page = $HTTP_GET_VARS['mod'];
}
else
{
$page = 'home';
}
// Check whether our page has a link in the db
$template = get_template($page);
if($template)
{
require( $template );
}
else
{
// Got false back from get_template, no link found
echo('Error: There is no file on this server with that name');
}
$server_db = "YOUR_SERVER_DB";
$user_db = "YOUR_USER_DB";
$password_db = "YOUR_PASSWORD_DB";
$db_name = "YOUR_DB_NAME";
$table = "YOUR_TABLE_NAME";
$link = mysql_connect($server_db,$user_db,$password_db);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_name);
$sql = sprintf("select Name, Link from %s",$table);
$rs = mysql_query($sql,$link);
while($row = mysql_fetch_assoc($rs)) {
echo "<a href='".$row['Link']."'>".$row['Name']."</a>";
}
mysql_free_result($rs);
mysql_close($link);