Page count function - javascript

Every time I get a visit to my index page I need to check if a record exists already in my database, if it does, it will need to update the field 'count' if not it will add a row.
I've managed to get it to create a row on visit, but cant seem to get it to update the count if the row already exists.
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Check to see if record exists
$sql = "SELECT * FROM page_tracking where name ="index.php"";
if (mysqli_query ($conn, $sql)) {
$sql= "UPDATE page_tracking SET count=count+1 where name= "index.php")";
}
else if {
//Insert Query
$sql = "INSERT INTO page_tracking (name, count)
VALUES ('index.php', '1')";
}
if (mysqli_query($conn, $sql)) {
echo "Thanks for visiting! Your visit has been recorded";
} else {
echo "Unfortunately we were unable to record your visit: " . $sql . "<br>" . mysqli_error($conn);
}
There's probably a really simple explanation! Issue is definitely with the code for 'check to see if record exists'

1) Dont use double quotes around index.php use single quotes.
Just run update query
$sql = "SELECT * FROM page_tracking where name ="index.php"";
$result = mysqli_query ($conn, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows) {
$sql= "UPDATE page_tracking SET count=count+1 where name= 'index.php'";
}else{
$sql = "INSERT INTO page_tracking (name, count) VALUES ('index.php', '1')";
}
if (mysqli_query($conn, $sql)) {
echo "Thanks for visiting! Your visit has been recorded";
} else {
echo "Unfortunately we were unable to record your visit: " . $sql . "<br>" . mysqli_error($conn);
}

Get the results and check whether it has records.
// Check to see if record exists
$sql = "SELECT * FROM page_tracking where name ="index.php"";
$query = mysqli_query ($conn, $sql);
$result=mysqli_fetch_all($query,MYSQLI_ASSOC);
if (count($result) > 0) {
$sql= "UPDATE page_tracking SET count=count+1 where name="index.php")";
}
else {
//Insert Query
$sql = "INSERT INTO page_tracking (name, count)
VALUES ('index.php', '1')";
}

In your code, you never executed the query. Only created it in a string.
if (mysqli_query ($conn, $sql)) {
$sql= "UPDATE page_tracking SET count=count+1 where name= "index.php")";
# execute the query
}
Also, not sure why this loose else if without a condition:
else if {
//Insert Query
An you may want to checkout the INSERT ... ON DUPLICATE KEY UPDATE statement, which can reduce your whole code to a single query if the file name is your unique key:
mysqli_query ($conn, "
INSERT INTO page_tracking (name, count)
VALUES ('index.php', 1)
ON DUPLICATE KEY UPDATE count=count+1
");

Please try this. Use single quote instead of double quote.
$link = mysql_connect("localhost", $mysql_user, $mysql_password);
mysql_select_db($database, $link);
$result = mysql_query("SELECT * FROM page_tracking where name ='index.php'", $link);
$num_rows = mysql_num_rows($result);
if($num_rows==1){
//Update Query
}else{
//Insert Query
}

Related

Can't delete on Angular

I'm trying to delete one line from a table, however and even following the examples on stackoverflow, I can't reach a solution.
One of the Important things before start, is that I have the url's hidden, so I don't see the Get url, even the splice don't delete the right line on the table.
HTML:
<button id="{{value.username}}" type='button' type="button" ng-click="delete(value.username, $index)" class="btn btn-primary">Delete</button></td>
JS
$scope.delete = function(deletingId, index){
console.log(deletingId);
$http.get("../admin/deleted.php?username=" + deletingId)
.success(function(data){
$scope.data.splice(index, 1);
console.log('dadasdas');
})
}
PHP
$id = $_GET ['username'];
$sql = "SELECT * FROM members";
$records = mysql_query($sql);
if(isset($_GET['username'])){
$id = $_GET ['username'];
$delete = "DELETE FROM members WHERE username= '$id'";
$res = mysql_query($delete) or die ("FAILED" .mysql_error());
}
Am I doing anything wrong ( the scope is working, the php src is correct, but even doing an echo on php it doesn't fulfill nothing) since I've the url's hidden is there anyway to make it as a post?
Thanks in advance
Try this (I will use Mysqli, because I don't use Mysql);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$id = $_GET['username'];
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if (strtolower($id) == strtolower($row['username'])) {
$sql = "DELETE FROM users WHERE id=".row['id'];
$conn->query($sql);
}
}
} else {
echo "No accounts registered!";
}
So, deleting stuff with SQL, is case sensitive. So, I hope/think you have a auto increment id in your database. Then this will 100% surely work!

Selecting row with multiple parameters (ajax and PHP)

Good Day,
I'm new to PHP/MySQL and I try to send a request from ajax and select a row in a database with multiple parameters.
Is this the good way to do that ?
AJAX (Jquery):
function readLine(name, firstname) {
$.ajax({
type: "post",
url: "./php/readLine.php",
dataType: 'json',
data: { name: name, firstname: firstname },
success: function(data) {
console.log(data);
}
error: function(data) {
console.log("An error occured!");
}
});
}
PHP:
<?php
$sql = "SELECT * FROM table1 WHERE firstname=".intval($_POST['firstname'])." AND name=".intval($_POST['name']);
$con = mysqli_connect("localhost", "root", "", "myDB");
if (!$con) {
die("Connection failed: " . mysqli_error($con));
}
$result = mysqli_query($con, $sql);
$to_encode = array();
while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
$to_encode[] = $row;
}
echo json_encode($to_encode);
mysqli_close($con);
?>
Thanks for your help.
You can do it using PDO with prepared statements, that'll make sure the user input is made safe. Like this:
try {
$db = new PDO('mysql:dbname=db_name;host=localhost', 'db_user', 'db_password');
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
$sql = "SELECT * FROM table1 WHERE firstname=:firstname AND name=:name";
$stmt = $db->prepare($sql);
$stmt->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STRING);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STRING);
$stmt->execute();
$result = $stmt->fetchAll();
echo json_encode($result);
Move the first 5 lines into an include, then you only need this code once.
Firstly, you should use prepared statements instead, as currently the code is susceptible to SQL Injection attacks. I cannot emphasise this enough, an attacker would be able to wreak havoc on your database with the code you currently have.
You should use something like the following (taken from the page linked above, and this comment on the same page). Note that I have removed the intval calls to your POSTed data, as I assume they are strings rather than integers.
$to_encode = array();
$mysqli = new mysqli("localhost", "root", "password", "myDB");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM table1 WHERE firstname=? AND name=?")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $_POST['firstname'], $_POST['name']);
/* execute query */
$stmt->execute();
/* instead of bind_result: */
$result = $stmt->get_result();
/* now you can fetch the results into an array - NICE */
while ($myrow = $result->fetch_assoc()) {
// use your $myrow array as you would with any other fetch
$to_encode[] = $myrow;
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
echo json_encode($to_encode);
$stmt = $con->prepare("SELECT * FROM table1 WHERE name=? and firstname=?");
$stmt->bind_param($name ,$firstname);
// set parameters and execute
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$name = mysqli_real_escape_string($con, $_POST['name']);
$stmt->execute();
$stmt->bind_result($to_encode);
$stmt->fetch();
echo json_encode($to_encode);

add more information to database without making a new database

I would like to know how users can add multiple images and new data. For example on the site that I'm doing, you can make a design and when you finish you upload it to the database along with your email address title of the design, keywords ect.
I would like to know how its possible to let the user create more designs and named them all in the same database just retrieve them with an email address. I would like to make a limit of 14 designs per email address. But with the database and code that I have now, it only lets one design it just updates every time a new design is created.
Can someone show me the way on how to do this? If you need more information please ask, thank you.
Here is my code:
$query='UPDATE shirt_table SET images="'.$_FILES['file4']['name'].'", images1="'.$_FILES['file1']['name'].'", images2="'.$_FILES['file2']['name'].'", images3="'.$_FILES['file3']['name'].'"
WHERE email= "'.$_SESSION['email'].'"';
if ($mysqli->query($query) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$mysqli->close();
I can see that the uploaded files have different names, you'll have to list the expected file names internally as an array and loop through it that way.
Another thing you need to take care of is when the user has like 13 designs uploaded already and wants to add 4 more designs. You need to decide if you will reject all or add only one. Here is an example I believe you can modify to your taste.
/*
CREATE TABLE `shirt_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email_address` varchar(50) DEFAULT NULL,
`image_path` varchar(100) DEFAULT NULL,
`date_created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)
*/
<?php
include("lib/dbcnx.inc.php");
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
$begin = 1;
$end = 5;
$max_uploads = 14;
$sel_query = "select count(*) from shirt_table where email = '".$_SESSION['email']."'";
$result = $mysqli->query($sel_query);
echo $sel_query."<br/>";
$numrows = $result->num_rows;
$counter = 0;
if ($numrows > 0) {
$row = $result->fetch_row();
$counter = $row[0];
}
if ($counter < $max_uploads) {
$saved_dir = "designs/";
$design_files = array($_FILES['file4']['name'], $_FILES['file3']['name'], $_FILES['file2']['name'], $_FILES['file1']['name']);
$query = "INSERT INTO shirt_table (email, image_path, date_created) values ";
for ($i=$begin; $i<=$end; $i++) {
$query = $query ."('".$email."', '".$saved_dir.$design_files[$i-$begin]."', now())";
if ($i < $end)
$query = $query.", ";
}
echo $query."<br/>";
if ($mysqli->query($query) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$mysqli->close();
} else {
echo "You have exceeded ...";
$mysqli->close();
}
?>

Save entire DOM in mysql

I am not sure if this is possible, but I am looking for a way to save the entire state of my webpage without explicitly saving each element to a database.
For example, I dynamically create buttons, checkboxes, text etc. until the webpage looks as it needs. Can I save the DOM as a string, or blob in a database, and parse it later the get the webpage back?
I have tried things like:
var doc = document.documentElement.outerHTML;
Then save the string to database but it doesn't work.
I am using an AJAX call to a PHP script to write to mysql:
jQuery.ajax({
type: "POST",
url: 'connect/database.php',
dataType: 'json',
data: {functionname: 'connect_to_database', arguments: [user_id, user, doc] },
success: function (obj, textstatus) {
if( !('error' in obj) ) {
}
else {
console.log(obj.error);
}
}
});
PHP looks like:
// connection script
$servername = "XXX";
$username = "XXX";
$password = "XXX";
$dbname = "XXX";
$user_id = $_POST['arguments'][0];
$user = $_POST['arguments'][1];
$string = $_POST['arguments'][2];
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO table (user_id, user, string) VALUES ('$user_id', '$user', '$string')";
# $sql = "UPDATE crows_nest SET json_string='$configuration' WHERE user = '$user'";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Use a prepared statement to prevent problems with special characters in the document string.
$stmt = $conn->prepare("INSERT INTO table (user_id, user, string) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $user_id, $user, $string);
if ($stmt->execute()) {
echo "New record created successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

increment a field manually in database using jquery and php [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I am trying to build a click button that increments value of the item in the database. I am using UPDATE method for this.
The problem is that whenever the update query is run, the value it takes from the databse to increment (or decrement) is zero. (0+1 = 1, 0-1 = -1)
require_once("C:/xampp/htdocs/Selfie/database/dbcontroller.php");
$db_handle = new DBController();
$image_id = $_POST["image_id"];
$active_user_id = $_POST["active_user_id"];
$query = "SELECT user_image_id from users where user_id='" . $active_user_id . "'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row['user_image_id'] == $image_id) {
echo "own image";
}
else
{
$query = "SELECT image_id from hearts where user_id='" . $active_user_id . "'";
$result = mysql_query($query);
if ($row = mysql_fetch_assoc($result)) {
if ($row['image_id'] == $image_id) {
$query = "UPDATE images SET image_hearts='image_hearts'-1 where image_id=" . $image_id;
$result = mysql_query($query);
$query = "DELETE FROM hearts WHERE user_id=" . $active_user_id;
$result = mysql_query($query);
$query = "UPDATE users SET user_like ='' where user_id=" . $active_user_id;
$result = mysql_query($query);
echo "just unlike";
}
else
{
$query = "DELETE FROM hearts WHERE user_id=" . $active_user_id;
$result = mysql_query($query);
$query = "UPDATE images SET image_hearts='image_hearts'-1 where image_id=" . $row['user_image_id'];
$result = mysql_query($query);
$query = "Select image_path from images where image_id=" . $image_id;
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$query = "UPDATE users SET user_like ='" . $row["image_path"] . " where user_id=" . $active_user_id;
$result = mysql_query($query);
$query = "UPDATE images SET image_hearts='image_hearts'+1 where image_id=" . $image_id;
$result = mysql_query($query);
$query = "INSERT INTO hearts (image_id , user_id) VALUES ('$image_id','$active_user_id')";
$result = mysql_query($query);
echo "unlike then like";
}
}
else
{
$query = "INSERT INTO hearts (image_id , user_id) VALUES ('$image_id','$active_user_id')";
$result = mysql_query($query);
$query = "UPDATE images SET image_hearts='image_hearts'+1 where image_id=" . $image_id;
$result = mysql_query($query);
$query = "Select image_path from images where image_id=" . $image_id;
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$query = "UPDATE users SET user_like ='" . $row["image_path"] . "' where user_id=" . $active_user_id;
$result = mysql_query($query);
echo "image liked successfully.";
}
}
This is my jQuery code:
function test_click(i_image_id, i_heart_id, i_active_user_id) {
var active_user_id = i_active_user_id;
var image_id = i_image_id;
var heart_id = i_heart_id;
jQuery.ajax({
url: "../Selfie/validations/add_like.php",
data: {
active_user_id: active_user_id,
image_id: image_id
},
type: "POST",
success: function(data) {
if (data == "own image")
{
alert('You are trying to like your own image You NARCISSIST');
}
else if (data == "just unlike")
{
$("*").removeClass("btn-heart-red animated bounce fa-heart-red");
alert('just unlike');
}
else
{
$("*").removeClass("btn-heart-red animated bounce fa-heart-red");
$("#" + heart_id).removeClass("animated rubberBand");
$("#" + heart_id).toggleClass("btn-heart-red animated bounce fa-heart-red");
}
alert(data);
}
});
}
This image_hearts='image_hearts'+1 remove the quotes; that's a column you're wanting to update and not the string literal. The same thing goes for 'image_hearts'-1
Check for errors on your queries, which would have helped you here.
http://php.net/manual/en/function.mysql-error.php
Plus, your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0 and removed as of PHP 7.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Footnotes:
If I may quote Marc's comment:
"in other words. 'image_hearts' + 1 is string literal plus integer, and unless that string literal contains digits at the start of it, will simply become 0 + 1 – Marc B"

Categories