Im trying to make an image click counter, so that when some one click on an image it updates hit column by 1.
Im having trouble with the syntax, as far as getting the row number that needs to be updated.
Later i want to use this hit column to sort the order that the images are displayed on the site.
If you feel like throwing me a bone and telling how to do that as well it would be much appreciated :)
connect.php
<?php
$servername = "*******";
$username = "********";
$password = "********";
$dbname = "********";
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
?>
art.php
<?php
require 'connect.php';
$sql = "SELECT * FROM art";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='art'>
<a href='img/".$row["name"].".jpg '
//part that I need help with
onclick='
<?php
include 'update_hits.php';
update_hit('$row');
?>'
target='_blank'>
<img src='img/".$row["name"]."_tnail.jpg' alt='".$row["name"]."' title='".$row["name"]." • ".$row["year"]." • ".$row["type"]."'/>
</a>
<p>
".$row["name"]." • ".$row["year"]." • ".$row["type"]."
</p>
</div>"
;
}
} else {
echo "0 results";
}
$conn->close();
?>
update_hits.php
<?php
require 'connect.php';
function update_hit($row){
$query = "SELECT 'hits' FROM 'art'";
if(#$query_run = mysql_query($query);){
$count = mysql_result($query_run, '$row' , 'hits');
$count_inc = $count + 1;
$query_update = "UPDATE 'art' SET 'hits' = '$count_inc'";
#$query_update_run =mysql_query($query_update);
}
}
?>
Finally got it to work
<?php
require 'connect.php';
$image = $_GET['image'];
//need to check whether file exists also
if(!empty($image)){
echo "<img src='".$image.".jpg'>"; // prefix full path if needed
$imagename = explode("/", $image);
$sql = "UPDATE `art` SET `hits`=`hits` +1 WHERE `name` = '".$imagename[1]."'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
?>
This is only the logic, your code is not perfect it needs many validation and additional checks. I have not tested this code check for syntax errors. Its only for you to get the logic on how to do this.
modified art.php
<?php
require 'connect.php';
$sql = "SELECT * FROM art";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='art'>
<a href='displayImg.php?image=".$row["name"]."' target='_blank'>
<img src='img/".$row["name"]."_tnail.jpg' alt='".$row["name"]."' title='".$row["name"]." • ".$row["year"]." • ".$row["type"]."'/>
</a>
<p>
".$row["name"]." • ".$row["year"]." • ".$row["type"]."
</p>
</div>"
;
}
} else {
echo "0 results";
}
$conn->close();
?>
new displayImg.php
<?php
require 'connect.php';
$image = $_GET['image'];
//need to check whether file exists also
if(!empty($image)){
echo 'img/'.$image.'jpg'; // prefix full path if needed
$sql = "UPDATE 'art' SET hits=hits+1 where name = ".$image;
$result = $conn->query($sql);
}
?>
Related
I'm trying to get a value from the database and compare it with whatever id href was set. But nothing happens.
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "products";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$id = $row["id"];
echo <<<EOT
<br>
<form action='index.php?$id' method="POST">
<input type='submit' name="submit" value="more">
</form>
EOT;
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
while($row = $result->fetch_assoc()) {
if ($_SERVER["QUERY_STRING"] == $row) {
echo 'you clicked something from the database' . $id;
}
}
}
$conn->close();
?>
Trying to eventually get a value from the database then individually show a description if the more href is clicked.
your answer has a high time complexity you can easily make you
SQL query
SELECT id FROM items WHERE id = ?
and if the rows number is 0 this is mean there is no record with this id
you can check row's number from num_rows
You will never see "you clicked something from the database" message because you already fetched the result from your query in the first loop, check this question why-cant-i-loop-twice-on-mysqli-fetch-array-results
An option is to save the result in an array to use it later in your second loop
//your first loop
$savedRows = [];
while($row = $result->fetch_assoc()) {
$savedRows[] = $row;
//the rest of your code
}
// ......
// your second loop
if (isset($_POST['submit'])) {
foreach($savedRows as $row) {
if ($_SERVER["QUERY_STRING"] == $row['id']) {
echo 'you clicked something from the database ' . $id;
}
}
}
Also note that if this is your actual code, you need to make the closing identifier of your herodoc EOT; the first character on it's line, otherwise the rest of the file will be part of this string
I have a index.php page Picture : http://i.imgur.com/UBorPdE.png
Website : http://www.vestigedayz.com/sala/clienti/index.php (User: Test123, pass: test)
<?php include("auth.php"); //include auth.php file on all secure pages )
$dbhost = 'host';
$dbuser = 'user';
$dbpass = 'pass';
$conn = mysql_connect("host", "user", "pass");
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("vestiged_sala")) {
echo "Unable to select vestiged_sala: " . mysql_error();
exit;
}
mysql_select_db("vestiged_sala");
$result = mysql_query("select * from users");
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["Antrenor"];
echo $row["PrimulContract"];
echo $row["ExpiraContract"];
}
mysql_free_result($result);
?>
ok, after that it comes HTML codes. I have this code
<h4>Bun venit, <?php echo $_SESSION['username']; ?> !
<hr>
Abonamentul tau expira pe data de: <?php echo $row["ExpiraContract"]; ?>
<hr>
Primul tau contract a fost facut pe data de : <?php echo $row["PrimulContract"]; ?>
<hr>
Pe data de <?php echo $row["antrenor"]; ?> va trebui sa platesti instructorul !
</h4>
But php won't show those rows. Only [user] row. The others it appears to be blank. When I add while ($row = mysql_fetch_assoc($result)) above of "Abonamentul tau" it gives me errors. What is the solution to my problem ? Because I know is something easy but I'm beginner and I can't figure it out.
in place of this line
$result = mysql_query("select * from users");
put these lines
$result = mysql_query("SELECT * FROM users WHERE username='$user' LIMIT 1");
while($row = mysql_fetch_array($result)){
$expire = $row['ExpiraContract'];
$primul = $row['PrimulContract'];
$antrenor = $row['Antrenor'];
}
But remember you have to declare empty variables before these line
$user = $_SESSION['username'];
$expire = '';
$primul = '';
$antrenor = '';
So, your full code is like this
//First define empty variables
$user = $_SESSION['username'];
$expire = '';
$primul = '';
$antrenor = '';
// add these lines in place of $result query
$result = mysql_query("SELECT * FROM users WHERE username='$user' LIMIT 1");
while($row = mysql_fetch_array($result)){
$expire = $row['ExpiraContract'];
$primul = $row['PrimulContract'];
$antrenor = $row['Antrenor'];
}
This is you html now
Abonamentul tau expira pe data de: <?php echo $expire; ?>
<hr>
Primul tau contract a fost facut pe data de : <?php echo $primul; ?>
<hr>
Pe data de <?php echo $antrenor; ?> va trebui sa platesti instructorul !
</h4>
Try this. If you have any problem then comment it. :)
Remove these lines if you try this first
while ($row = mysql_fetch_assoc($result)) {
echo $row["Antrenor"];
echo $row["PrimulContract"];
echo $row["ExpiraContract"];
}
I have a very simple use case where I am checking if a certain value is present in the table and it always seems to fail.This is my php code.
<?php
include "config.php";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$dbname);
if(!$con)
{
echo "Connection Error".mysqli_connect_error();
}
else{
//echo "";
}
$device_id = $_POST["device_id"];
$check = "SELECT magazine_id FROM registered_buyers WHERE device_id = $device_id";
$rs = mysqli_query($con,$check);
if(mysqli_num_rows($con,$rs) == 0)
{
$jsonarray = $_POST["jsonarray"];
echo "This will be inserted".$jsonarray;
}else
{
echo "User already registered";
}
?>
Can anyone please point out my mistake.Any help or suggestion is welcome.Thank you.
You can try to follow this code.
<?php
include "config.php";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$dbname);
if(!$con){
echo "Connection Error".mysqli_connect_error();
}
$device_id = $_POST["device_id"];
$check = "SELECT magazine_id FROM registered_buyers WHERE device_id = ".$device_id;
$rs = mysqli_query($con, $check);
if(mysqli_num_rows($rs) == 0){
$jsonarray = $_POST["jsonarray"];
echo "This will be inserted".$jsonarray;
}else{
echo "User already registered";
}
?>
since i dont have enough rep to add a comment, i will consider the device_id is string, if so try something like this:
"SELECT magazine_id FROM registered_buyers WHERE device_id = '$device_id'";
add '
PROBLEM: I got a problem updating my input into sql using PHP, the PHP updates all empty values into sql which I don't want to.
ACHIEVEMENT: So I hope to achieve when user submit their data either empty or filled then PHP might be able to pickup and update only filled data into my sql. I tried using input with value=">php echo here<" but it won't work with textarea, so I couldn't find any solution since I'm new to PHP and SQL. Tried to find similar posts but I couldn't make them work like I wanted to :(
<?php include 'config/sqlconnect.php'; ?>
<form method="post" action"config/sqlconnect.php">
</p>MainPage info</p>
<input type="text" name="mainPageInfo"/>
<br>
</p>MiddlePage info</p>
<textarea name="middlePageInfo"></textarea>
<br>
</p>Container info</p>
<input type="text" name="containerInfo"/>
<br>
</p>Content</p>
<input type="text" name="content"/>
<br>
</p>Second content</p>
<input type="text" name="secondContent"/>
<input type="submit" name="submit" class="btn-block"/>
<br>
</form>
in PHP script
<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "pagesDb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$sql = "SELECT * FROM myPages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$mainPageInfo = $row['mainPageInfo'];
$middlePageInfo = $row['middlePageInfo'];
$containerInfo = $row['containerInfo'];
$content = $row['content'];
$secondContent = $row['secondContent'];
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
$mainPageInfo = $_POST['mainPageInfo'];
$middlePageInfo = $_POST['middlePageInfo'];
$containerInfo = $_POST['containerInfo'];
$content = $_POST['content'];
$secondContent = $_POST['secondContent'];
$sql = "UPDATE myPages SET mainPageInfo='$mainPageInfo',
middlePageInfo='$middlePageInfo',
containerInfo='$containerInfo',
content='$content',
secondContent='$secondContent'
WHERE id=0";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
Second Attempts: It doesn't update my data somehow... please help I tried more than 8 hours with no results :(
if (isset($_POST['submit'])) {
foreach($_POST as $name => $value) {
$sql = "UPDATE myPages SET $name = '$value' WHERE id=1";
}
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
Help would be appreciated, thanks everyone!
Using your Second Attempt as a starting point.
The problem with just using the POST array without being specific is that, in this example you are going to try an update a column on the database called submit i.e. your submit button. Later there may be data on the page that belongs in 2 or more tables.
So create an controlling array containing all the field names from the form that you want to process onto your table.
$db_fields = array('mainPageInfo', 'middlePageInfo', 'containerInfo',
'content', 'secondContent');
$sql = ''; // will hold the query we build dynamically
// was this a user sending data
if ( $_SERVER['REQUEST_METHOD' == 'POST' ) {
foreach($db_fields as $fieldname) {
if ( ! empty($_POST[$fieldname] ) {
$sql .= "$fieldname = '{$_POST[$fieldname]}', ";
}
}
}
$sql = rtrim($sql, ','); // remove the trailing comma
$sql = "UPDATE myPages SET $sql WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
I need to display every new row in bold that will be stored in database in php and and then display it. Only the new row should be bold. Here's what I did
<?php
//connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "resultdb"; //my database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
$name=$_POST['name'];
$roll=$_POST['roll'];
$m1=$_POST['m1'];
$m2=$_POST['m2'];
$m3=$_POST['m3'];
//ISNERT DATA INTO TADABASE
$sql="INSERT INTO markstb(name,rollno,sub1,sub2,sub3) VALUES('$name','$roll','$m1','$m2','$m3')";
if($conn->query($sql)===true)
{
//ketp id column in DB to auto_increment
$last_id=mysqli_insert_id($conn);
echo " NEW RECORD INSERTED"."<br>";
if($last_id>0)
{
$sql3="SELECT * FROM markstb WHERE id='$last_id'";
$result = $conn->query($sql3);
echo "<table border='2' bordercolor='black' ";
echo"<tr><td>NAME</td><td>ROLLNO</td><td>SUB1</td><td>SUB2</td><td>SUB3</td></tr>";
while($row=$result->fetch_assoc())
{
echo"<tr><td><b>".$row['name']."</td><td><b>".$row['rollno']."</td><td><b>".$row['sub1']."</td>"
."<td><b>".$row['sub2']."</td><td><b>".$row['sub3']."</td>";
}
echo "</table>";
}
else
{
echo"check last_id";
}
echo "<br><br><br><br>";
}
else
{
echo "ERROR".$sql."<br>".$conn->error;
}
//RETRIVE DATA FROM DATABASE
$sql2="SELECT * FROM markstb ORDER BY name";
//$result=$conn->query($sq2);
$result = $conn->query($sql2);
echo "<table border='2' bordercolor='black' ";
if($result->num_rows > 0)
{
echo"<tr><td>NAME</td><td>ROLLNO</td><td>SUB1</td><td>SUB2</td><td>SUB3</td></tr>";
while($row=$result->fetch_assoc())
{
echo"<tr><td>".$row['name']."</td><td>".$row['rollno']."</td><td>".$row['sub1']."</td>"
."<td>".$row['sub2']."</td><td>".$row['sub3']."</td>";
}
echo "</table>";
}
else
{
echo" 0 rows";
}
$conn->close();
?>
In above program I have ony fetched the row which is new and made it bold
but I have to show all data that is in database and make only row bold which is new, which is entered by the user.
In your last while loop you could try:
if($row['id'] == $last_id){
//echo "your row that is
//bold
}else{
// echo you regular row
}
When you are printing out the data, you can do this type of thing inside of the echo statement:
echo "<tr" . $last_id === (int) $row['id] ? . ' class="bold"' : null; . "><td>...";
So that means, when you are printing the tag, you are checking if the row id matches the last id, if so you are additionally printing a html class of "bold".
Of course, it's up to you to use css to target this selector and actually make it bold.
That is called the 'ternary if'. It looks like this:
condition ? do this if true : do this if false;