I was looking for a way to update the count for the database after finding the result of a product but it keeps returning an error and/or not updating the count. I found ways to update the counts out right but not after finding a result. If i'm blind please redirect me. My apologies if I overlooked anything. RAM
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
require_once '../connect/connect.php';
$usertable = "UPC_Product";
$yourfield2 = "Product";
$yourfield1 = "UPCA";
$yourfield3 = "Gluten Free";
$yourfield4 = "Company";
$yourfield5 = "search_cnt";
$yourfield6 = "CompName";
$yourfield7 = "id";
$search_id = $_POST["search_id"];
//Connecting to your database
mysql_connect($hostname, $username, $password) or die("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable WHERE UPCA = $search_id";
$result = mysql_query($query);
if ($result) {
while ($row = mysql_fetch_array($result)) {
$name = $row["$yourfield2"];
$upca = $row["$yourfield1"];
$gluten = $row["$yourfield3"];
$count = $row["$yourfield5"];
$id = $row["$yourfield7"];
}
//update count
$ucount = "UPDATE $usertable SET search_cnt = ($count + 1)";
mysql_query($ucount);
}
?>
<head>
<link rel="icon"
type="image/png"
href="../images/GluteFreefavicon.jpg">
<meta name="viewport" content="width=device-width">
<title>Result Page</title>
<meta http-equiv="Content-Language" content="English" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="/style.css" media="screen" />
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-39600334-1', 'glutefree.com');
ga('send', 'pageview');
</script>
</head>
<body>
<div id="wrap">
<div id="top"></div>
<div id="content">
<div class="header">
<img src="/images/glutefreefacebookbanner.jpg"/>
</div>
<div class="breadcrumbs">
<center> Home · Search · Application · Register · Contact Us · About Us · Games
</center>
</div>
<div class="result">
<center>Your Results
<br/>
</center>Product:
<?php echo $name; ?>
<br/>
<div class="product">Gluten Free?
<?php echo $gluten; ?>
<br>
<br>UPC:
<?php echo $upca;?>
<br>Search count:
<?php echo $count;?>
<br/>
</div>
</div>
<p>No Result? Click here to fill out information on the product you were searching for.</p>
</div>
<div id="bottom"></div>
</div>
<div id="footer">
</a>
</div>
</body>
</html>
correction 1 :- I think you need to write your update query below the while loop. because you are using $count variable before creating it.
Also please specify if you need to increase count for individual row or total.
If you need to update count for individual row then you have write query inside while loop.
UPDATE $usertable SET search_cnt = ($count + 1) WHERE id_column_name = $id;
correction 2:- You are calling mysql_query($ucount); in wrong place. this should be below update query.
Correction 3 :- as $count is your count number then obviously it will not be your column name , write down you column name in update query.
UPDATE $usertable SET count_column_name = ($count + 1)
Corrected Block of code:-
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
require_once '../connect/connect.php';
$usertable = "UPC_Product";
$yourfield2 = "Product";
$yourfield1 = "UPCA";
$yourfield3 = "Gluten Free";
$yourfield4 = "Company";
$yourfield5 = "search_cnt";
$yourfield6 = "CompName";
$yourfield7 = "id";
$search_id = $_POST["search_id"];
//Connecting to your database
mysql_connect($hostname, $username, $password) or die("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable WHERE UPCA = $search_id";
$result = mysql_query($query);
if ($result) {
while ($row = mysql_fetch_array($result)) {
$name = $row["$yourfield2"];
$upca = $row["$yourfield1"];
$gluten = $row["$yourfield3"];
$count = $row["$yourfield5"];
$id = $row["$yourfield7"];
}
//update count
// Please write here count column name not $count. I have write count at this time.
$ucount = "UPDATE $usertable SET search_cnt = ($count + 1)";
mysql_query($ucount);
}
?>
All you need to do is rearrange a function to get the correct count. Below should be the right code.
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
require_once '../connect/connect.php';
$usertable = "UPC_Product";
$yourfield2 = "Product";
$yourfield1 = "UPCA";
$yourfield3 = "Gluten Free";
$yourfield4 = "Company";
$yourfield5 = "search_cnt";
$yourfield6 = "CompName";
$yourfield7 = "id";
$search_id = $_POST["search_id"];
//Connecting to your database
mysql_connect($hostname, $username, $password) or die ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable WHERE UPCA = $search_id" ;
$result = mysql_query($query);
if ($result) {
while($row = mysql_fetch_array($result)) {
$name = $row["$yourfield2"];
$upca = $row["$yourfield1"];
$gluten = $row["$yourfield3"];
$count = $row["$yourfield5"];
$id = $row["$yourfield7"];
}
}
$ucount = "UPDATE $usertable SET $count = ($count + 1)";
mysql_query($ucount) or die(mysql_error());
?>
To be more specific - You were trying to call:
$ucount = "UPDATE $usertable SET $count = ($count + 1)";
before you actually updated the $count method in the while loop.
Related
This code leaks information from the login page when a route that does not exist is being tried to navigate at.
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Login</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="uname">
password: <input type="password" name="upass">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$loginusername = $_POST['uname'];
$loginpassword = $_POST['upass'];
if (empty($loginusername) || empty($loginpassword)) {
echo "Please enter username and password";
} else {
$user = getEnv('USER');
$password = getEnv('PASSWORD');
$database = getEnv('DATABASE');
$table = getEnv('SONGS');
$db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
$query = "SELECT * FROM $table where user_name = :username and password = :loginPassword";
$statement = $db->prepare($query);
$statement->bindParam(":username",$loginusername, PDO::PARAM_STR);
$statement->bindParam(":loginPassword",$loginpassword, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll();
if(!$result) {
echo "<p>No result!</p>";
exit;
} else {
$userid = $result[0][0];
$username = $result[0][1];
}
}
}
?>
</body>
</html>
This is an indexing page which will index all articles that are in the website.
<html>
<head>
<title>Some title</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
Return
<?php
if (isset($_GET['file'])) {
$file = $_GET['file'];
$file = file_get_contents($file);
echo "$file";
echo '<br />Index';
}
else {
$user = getEnv('USER');
$password = getEnv('PASSWORD');
$database = getEnv('DATABASE');
$table = getEnv('ARTICLES');
$db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
$query = "SELECT * FROM $table";
$stmt = $db->prepare($query);
$stmt = $db->query($query);
echo "<ul>";
foreach($stmt as $row) {
$href = $row[2];
$title = $row[1];
echo "<li> <a href='/myPage?file=../dir/$href'>$title</a> </li> ";
}
echo "</ul>";
}
?>
</body>
</html>
When this href echo "<li> <a href='/myPage?file=../dir/$href'>$title</a> </li> "; is changed manually at browser at suppose this route /myPage/?file=../login.php it will cause to leak code from the login file, which can uncover to the attack some crucial information about my backend setup. Is there any way how to patch this problem.
Yes, it's easily avoided by sanitizing your input.
Structures such as this
if (isset($_GET['file'])) {
$file = $_GET['file'];
$file = file_get_contents($file);
are highly problematic.
But there isn't a one-size-fits-all solution without knowing what the legit files that you want to allow to be referenced are.
Roughly how many valid files are there ? are they all located in the same directory ? do they follow some sort of specific naming convention ? do they all have the same extension (or lack any at all) ?
Edit: I suspect you'll want something along these lines. I haven't tested it, so it's possible i made a typo somewhere, but it shouldn't suffer from the same vulnerabilities atleast.
<html>
<head>
<title>Some title</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
Return
<?PHP
$user = getEnv('USER');
$password = getEnv('PASSWORD');
$database = getEnv('DATABASE');
$table = getEnv('ARTICLES');
$db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
$filekey = 'ref';
$dbcolumn = 'href'; // <--- should match the name of the column in mysql
if (isset($_GET[$filekey]) && $request = $_GET[$filekey]) {
$stmt = $db->prepare("SELECT $dbcolumn FROM $table WHERE $dbcolumn = ?");
$stmt->execute([ $request ]);
if ( $records = $stmt->fetchAll(PDO::FETCH_ASSOC)
&& !empty($records)
&& $record = reset($records)
&& isset($record[$dbcolumn])
&& $request = $record[$dbcolumn]
) {
echo file_get_contents("../dir/$request");
echo '<br />Index';
} else {
die('Access denied');
}
} else {
$query = "SELECT * FROM $table";
$stmt = $db->prepare($query);
$stmt = $db->query($query);
echo "<ul>";
foreach($stmt as $row) {
$href = $row[2];
$title = $row[1];
printf('<li><a href='/myPage?%s=%s'>%s</a></li>',
$filekey,
htmlentities($href, ENT_QUOTES),
htmlentities($title, ENT_QUOTES)
);
}
echo "</ul>";
}
?>
</body>
</html>
Make sure you set $dbcolumn correctly (should match the mysql column name), and optionally change $filekey to whatever you want to see in the URL.
This fixes your security problem: it only allows filenames to be specified in the URL, that actually exist in your database table, so it cant be used to pull random files anymore. If someone tries to manually change thevalue in the URL to something not in the database they get the error above.
It also fixes potential problems with the title in the listing, which was being output raw (i added htmlentities). Depending on the type of content inside the files, you may want to wrap a htmlentities call around file_get_contents() aswell, but don't do that if there is actual html inside those files.
I did see some other oddities , such as that you create a prepared statement and then don't use it :) but that has no security implications in this case, i left it as is.
Let me explain what I want to.
I want to add a value in a list with db add without page change when I input in form, and click submit.
but in this code, I must refresh one more time to add, and also added twice a time.
How can I do that?
<?php
$conn = mysqli_connect('127.0.0.1','MYID','MYPASS','MYDB');
$sql = "SELECT * FROM MYTABLE";
$rs = mysqli_query($conn, $sql);
$list = '';
while($row = mysqli_fetch_array($rs)) {
$list = $list."<li>{$row['title']}</li>";
}
$article = array(
'title' => 'Welcome!',
'description' => 'Hello, Web!'
);
if (isset($_GET['id'])){
$filtered_id = mysqli_real_escape_string($conn, $_GET['id']);
$sql = "SELECT * FROM topic WHERE id={$filtered_id}";
$rs = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($rs);
$article['title'] = $row['title'];
$article['description'] = $row['description'];
}
if ($_POST['title'] != null){
$sql_in = "INSERT INTO topic (title, description, created) VALUES ('{$_POST['title']}', '{$_POST['description']}', NOW())";
$rs_in = mysqli_query($conn, $sql_in);
if ($rs_in === false) {
$msg = mysqli_error($conn);
} else {
$msg = 'Success.';
}
} else {
$msg = 'Fill in';
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WEB</title>
</head>
<body>
<h1>WEB</h1>
<ol>
<?=$list?>
</ol>
<details>
<summary>Create</summary>
<form action="./index.php" method="POST">
<p><input type="txt" name="title" placeholder="title"></p>
<p><textarea name="description" placeholder="description"></textarea></p>
<p><input type="submit"></p>
<p><?=$msg?></p>
</form>
</details>
</body>
</html>
<h2><?=$article['title']?></h2>
<?=$article['description']?>
</body>
</html>
In php realtime isn't a thing but there is a workaround you can use events services like pusher https://pusher.com/docs and receive the events in client side instantly .
there other website offers this so do your search before choosing them also you can always build your event server in node.js , c# , go
How would I output the selected data from the database over a certain amount of pages.
For example I'd like 20 result per page and it automatically adds the extra pages needed (bit like google search pages but no search is needed as I am getting everything from the database).
Sorry for a bad explanation and also badly indented code, new to stackoverflow. I've tried putting just the php, rest of the page isn't complete or I removed the unnecessary code, feel free to improve as well.
At the moment I am just calling all the data onto one page using very simple
code
<?php
session_start();
if(isset($_POST['logout'])) {
unset($_SESSION['Username']);
session_destroy();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Backend</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="" style="min-width: 1024px; max-width: 1920px; margin: 0 auto; min-height: 1280px; max-height: 1080px;">
<?php
if (isset ($_SESSION['Username']))
{
?>
<button onclick="location.href = 'logout.php';">Logout</button>
<?php
if (isset ($_SESSION['Username']))
{
echo "";
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "request";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM request";
$result = $conn->query($sql);
$sql = "SELECT * FROM request ORDER BY id DESC";
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
if (isset ($_SESSION['Username']))
{
?>
<div align="center">
<div class="requests">
<p><?php echo $row["Name"]; ?></p>
<p><?php echo $row["Number"]; ?></p>
<p><?php echo $row["Song"]; ?></p>
</div>
</div>
<?php
}else{
header("Location: index.php");
}
}
} else {
echo "0 requests";
}
}
mysqli_close($conn);
?>
Let's see an example of pagination in PHP. Before that, we need to understand what pagination is. Result pagination is quite simple.
We do a search on a certain DataBase table, and with the result of the search, we divide the number of records by a specific number to display per page.
Related: Data pagination in PHP and MVC
For example a total of 200 records, and we want to display 20 per page, we will soon have 200/20 = 10 pages. Simple, right? Well let's go to the code then.
First connect to MySQL:
<?php
$conn = mysql_connect("host","user","pass");
$db = mysql_select_db("database");
?>
Now let's create the SQL clause that should be executed:
<?php
$query = "SELECT * FROM TableName";
?>
Let's get to work ... Specify the total number of records to show per page:
<?php
$total_reg = "10"; // number of records per page
?>
If the page is not specified the variable "page" will take a value of 1, this will avoid displaying the start page 0:
<?php
$page=$_GET['page'];
if (!$page) {
$pc = "1";
} else {
$pc = $page;
}
?>
Let's determine the initial value of the limited searches:
<?php
$begin = $pc - 1;
$begin = $begin * $total_reg;
?>
Let's select the data and display the pagination:
<?php
$limit = mysql_query("$query LIMIT $begin,$total_reg");
$all = mysql_query("$query");
$tr = mysql_num_rows($all); // checks the total number of records
$tp = $tr / $total_reg; // checks the total number of pages
// let's create visualization
while ($dados = mysql_fetch_array($limit)) {
$name = $data["name"];
echo "Name: $name<br>";
}
// now let's create the "Previous and next"
$previous = $pc -1;
$next = $pc +1;
if ($pc>1) {
echo " <a href='?page=$previous'><- Previous</a> ";
}
echo "|";
if ($pc<$tp) {
echo " <a href='?page=$next'>Next -></a>";
}
?>
Ready, your pagination in PHP is created!
I'm trying to add a button that generates dummy data into a table with 1 click
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
include("classes/db.class.php");
$currentTime = time();
$totalUsers = '20000';
$usersUS1 = '5000';
$usersUS2 = '5263';
$usersFR1 = '8000';
$usersHK1 = '7425';
$usersUK1 = '0';
if(!empty($_POST))
{
$currentTime = time();
$db = new db();
$sql = "INSERT into connections (users, us1, us2, fr1, hk1, time, uk1) VALUES
('".$db->conn->real_escape_string($totalUsers) ."' ,
'". $db->conn->real_escape_string($usersUS1) ."' ,
'". $db->conn->real_escape_string($usersUS2) ."' ,
'". $db->conn->real_escape_string($usersFR1) ."' ,
'". $db->conn->real_escape_string($usersHK1) ."',
'". $db->conn->real_escape_string($currentTime) ."',
'". $db->conn->real_escape_string($usersUK1) ."')";
$result = $db->conn->query($sql);
return $result;
}
?>
However everytime I press the button, I receive 0 errors and nothing gets stored in the DB.
The php code and html are on the same page.
Does anyone know what's causing the problem?
EDIT:
DB class:
<?php
class db
{
private $m_sHost = "localhost";
private $m_sUserlogin = "root";
private $m_sPassword = "root";
private $m_sDatabase = "radius";
public $conn;
public function __construct()
{
$this->conn = new mysqli($this->m_sHost, $this->m_sUserlogin, $this->m_sPassword, $this->m_sDatabase);
}
}
?>
and the form I use to post:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>screen wall</title>
<link rel="stylesheet" type="text/css" href="styles/style.css">
<!--<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>-->
<script src="scripts/d3-3.5.2/d3.js"></script>
</head>
<body>
<p> Current Timestamp:<?php echo time(); ?> </p>
<form method="POST">
<input type="text" required="required" name="titel" value="test field :)">
<button type="submit" id="generateBtn">Add Data</button>
</form>
</body>
Again, HTML and PHP are on the same page.
First thing first: You should not be using the real_escape_string since the input is not from the user whereas it is hard coded in the code itself.
Secondly an alternative way to rectify the issue is you can use
if (!mysqli_query($db->conn,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
instead of
$result = $db->conn->query($sql);
Hope this helps.
Thank you
Hello i'm currently trying to create a blog for a school project and this is the code i've come up with.
<html>
<?php
$connection['host'] = '127.0.0.1';
$connection['user'] = 'root';
$connection['password'] = 'ascent';
$connection['webdb'] = 'login';
$connection['newstable'] = 'news';
if (isset($_GET['newsid']))
{
$id = (int)$_GET['newsid'];
connect::selectDB('webdb');
$result = mysql_query("SELECT * FROM news WHERE id='".$id."'");
$row = mysql_fetch_assoc($result); ?>
<div class='box_two_title'><?php echo $row['title']; ?></div>
<?php
Some cool way to post the "body" row here.
?>
</html>
Basicly i just want it to post the news on the website, i've loaned a bit of code from here and there and there's a couple of errors whenever i try. Help is greatly appreciated. :-)
You forgot the closing curly bracket, add <? } ?> before the closing <html> tag.
I have seen your code actually there are some errors in your code so firstly you have to connect with mysql database connection and then select DB. i am giving you the correct code so try this definitely it will help to create your blog.
<html>
<?php
$connection['host'] = '127.0.0.1';
$connection['user'] = 'root';
$connection['password'] = 'ascent';
$connection['webdb'] = 'login';
$connection['newstable'] = 'news';
if (isset($_GET['newsid']))
{
//code to set database connection
$link = mysql_connect($connection['host'], $connection['user'], $connection['password']);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// make login the current db
$db_selected = mysql_select_db($connection['webdb'], $link);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
//get news id
$id = (int)$_GET['newsid'];
$result = mysql_query("SELECT * FROM news WHERE id='".$id."'");
$row = mysql_fetch_assoc($result); ?>
<div class='box_two_title'><?php echo $row['title']; ?></div>
<?php // Some cool way to post the "body" row here. } ?> </html>
PHP is basically complaining, because you didn't close the curly brackets { of your if clause.
<html>
<?php
$connection['host'] = '127.0.0.1';
$connection['user'] = 'root';
$connection['password'] = 'ascent';
$connection['webdb'] = 'login';
$connection['newstable'] = 'news';
if (isset($_GET['newsid']))
{
$id = (int)$_GET['newsid'];
connect::selectDB('webdb');
$result = mysql_query("SELECT * FROM news WHERE id='".$id."'");
$row = mysql_fetch_assoc($result); ?>
<div class='box_two_title'><?php echo $row['title']; ?></div>
<?php
// Some cool way to post the "body" row here.
}
?>
</html>
Besides, although you're just starting with PHP, you should use PDO or mysqli to access the database. the mysql_X functions are deprecated.
When at least while developing check the error, MySQL might be returning to see why to query failed.