Basically I am trying to make it check if the user has their ID in the database and if they do have it in there it updates it putting $page as 'lastpage' in the database. It also checks to make sure that the value it has set inside there now is less than $page, if it isn't than it does nothing.
If the user doesn't have there ID in there than it should add it with whatever $page is set to.
The problem is that it isn't updating in the database at all.
This is the code I got so far, anyone got ideas?
session_start();
if(!isset($_SESSION['id'])) {
header("Location: ../../index.php");
} else {
}
include '../../connect.php';
include '../../users_func.php';
$id = $_SESSION['id'];
$page = 3;
$sql_chk = " select * from html where id = '$id' and lastpage = '$page' ";
$rs_chk = mysql_query($sql_chk);
$num_chk = mysql_num_rows($rs_chk);
if ($num_chk == 0) {
mysql_query("INSERT INTO `html` (`id`, `lastpage`) VALUES ('$id', '$page') ");
} else {
$sql = "UPDATE html SET lastpage='$page' WHERE id='$id' and lastpage < $page";
mysql_query($sql) or die("MYSQL Query Failed : " . mysql_error());
}
Your code is overly verbose, and those 3 queries would be replaced with a single
INSERT INTO html (id, lastpage) VALUES ($id, $page)
ON DUPLICATE KEY UPDATE lastpage = IF(lastpage < VALUES(lastpage), VALUES(lastpage), lastpage)
I know you are going to change the code to mysqli or PDO and all, but your existing code should check for errors
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
In your code, it's quite possible mysql_num_rows($rs_chk) is checking on an invalid resource $rs_chk.
Related
What I want is that php check if the client IP address is the same one which in the DB if it already exists, if not to insert new data.
well, it works if the client isn't already inserted in the database, but if he already exists php is skipping the update and trying to insert it again in the database............
I don't know whats wrong with it and couldn't figure out.
Here is my code:
<?php
$corruser = $_SESSION['user_name'];
$client_ip = $_SERVER['REMOTE_ADDR'];
require_once 'connections/dbc.php';
if (!$conn) {
echo "Error connecting the database";
exit();
} else{
$GUI = "SELECT * FROM `customers` WHERE user_name='$corruser'";
$GUI_response = mysqli_query($conn, $GUI);
if (!$row = mysqli_fetch_assoc($GUI_response)) {
echo "Error while query the database";
exit();
} else{
$customer_id = $row['customer_id'];
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$check_response = mysqli_query($conn,$check);
$check_result = mysqli_fetch_array($check_response, MYSQLI_NUM);
if ($check_result[0] > 1) {
$update_ip = "UPDATE `users-ipdb` SET `client_ip`='$client_ip' WHERE customer_id='$customer_id' AND user_name='$corruser' ";
$update_ip_result = mysqli_query($conn, $update_ip);
if (!$update_ip_result) {
echo "ERROR UPDATING DATA BASE";
exit();
}
} else{
$insert_new = "INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`) VALUES ('$customer_id','$corruser','$client_ip')";
$insert_new_result= mysqli_query($conn, $insert_new);
if (!$insert_new_result) {
echo "Error inserting new data in the database";
exit();
}
}
}
}
?>
I think you made an error with this code :
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$user_name variable doesn't exist, you should replace it with $corruser
That's why the code never goes into the UPDATE
First, make sure that your condition does work as expected. If customer_id is not a number the following line:
if ($check_result[0] > 1) {
can be possibly evaluated as if(0 > 1) let you read this:
Comparing String to Integer gives strange results.
The other comments mention "UPSERTS" which are explained here https://mariadb.com/kb/en/library/insert-on-duplicate-key-update/
The basic idea is that you can do
INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`)
VALUES ('$customer_id','$corruser','$client_ip')"
ON DUPLICATE KEY UPDATE client_ip='$client_ip';
and you get rid of the all the php logic. For this to work properly customer_id and user_name must be both part of the PRIMARY KEY.
If you need to query multiple tables, you can use joins - if you use ON DUPLICATE KEY UPDATE you don't need them, but still a good thing to know - https://mariadb.com/kb/en/library/join-syntax/
Last, but not least - it is a good habit to escape any value which may come from other sources. Maybe it is not your case, but some people tend to create usernames like Joe';DROP TABLE mysql.user;SELECT ' and it will destroy your database, because your query will become
SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='Joe';DROP TABLE mysql.user;SELECT ''
So be careful.
<?php
include('core/init.php');//database connection
if(isset($_POST['btn_submit'])){
$sqlQuery = mysql_query("UPDATE `position` SET `ATR`='".mysql_real_escape_string($_POST['ATR'])."',
$resultQuery = mysql_query($connection, $sqlQuery) or die (mysql_error($connection));
if(mysql_affected_rows($resultQuery) > 0){
echo "updated";
}else{
echo "failed";
}
header('Location:position2.php');
$result = mysql_query("SELECT * FROM position WHERE ID='" .$_POST["id"]. "'");
$row2 = mysql_fetch_array($result);
}
?>
//What this code does it it updates the database based on user input and I am trying to loop through each of the user input as update and display but it doesn't seem to work
($_POST['ATR'])."',
Is missing a closing "
Also formatting code makes it easier to read and debug.
Hello I want to make a like system using PHP and MySQL when clicked on the like Button i also insert Data in the database but there is an error database value inserted but like value as 0 no increment and undefined error occurs . Can anybody help me solving this problem
There is my Like button code :
<?php
//// work with like box
$get_likes = mysqli_query($con,"SELECT * FROM `likes`");
if (mysqli_num_rows($get_likes)===1) {
$get = mysqli_fetch_assoc($get_likes);
// $uid = $get['uid'];
$total_likes = $get['total_likes'];
//echo $uid;
$total_likes = $total_likes + 1;
//echo $total_likes++;
}
if (isset($_POST['likebutton_'])) {
$like = mysqli_query($con,"UPDATE `likes` SET `total_likes` = '$total_likes'") or die(mysqli_error($con));
//$insert_Data = mysqli_query($con,"INSERT INTO `likes` (`uid`) VALUES('$username')") or die(mysqli_error($ocn));
header("Location:home.php");
}
else
{
echo "Error";
}
?>
this code work fine without insert Data
There is My liked with Data Insertd Code
<?php
////work with like box
$get_likes = mysqli_query($con,"SELECT * FROM `likes`");
if (mysqli_num_rows($get_likes)===1) {
$get = mysqli_fetch_assoc($get_likes);
// $uid = $get['uid'];
$total_likes = $get['total_likes'];
//echo $uid;
$total_likes = $total_likes + 1;
//echo $total_likes++;
}
if (isset($_POST['likebutton_'])) {
$like = mysqli_query($con,"UPDATE `likes` SET `total_likes` = '$total_likes'") or die(mysqli_error($con));
$insert_Data = mysqli_query($con,"INSERT INTO `likes` (`uid`) VALUES('$username')") or die(mysqli_error($ocn));
header("Location:home.php");
}
else
{
echo "Error";
}
?>
this is output i want to display my font-end page <?php echo $total_likes ;?> but it occur error
The error is Undefined Variable
I also try $total_likes="";
as global but still not work
Your code suffers from a race condition. What you should be doing is this pattern:
INSERT INTO likes (uid, total_likes) VALUES (?, 1)
ON DUPLICATE KEY SET total_likes=total_likes+1
Where you use bind_param to set the placeholder value to your UID.
Note that in your one query you set the total count of all likes to be +1. This is a huge mistake.
I have the following PHP script that I am trying to execute. Its very simple yet I am overlooking something since it is not working correctly. If a user toggles a radio button, this script is called and the page is refreshed. However, the "enabled" column in MySQL never updates going from "0" to "1". If I manually enter the value of the enabled column to "1" then the script executes updating the value of the enabled column back to "0" but never to "1" again. What am I overlooking?
$sql="SELECT enabled FROM somecolumn.persist";
$row = mysql_fetch_row($sql);
$enabled=$row[0];
if ($enabled==0) {
$query="UPDATE `somecolumn`.`persist` SET `enabled` = '1' WHERE `persist`.`enabled` =0";
} else {
$query="UPDATE `somecolumn`.`persist` SET `enabled` = '0' WHERE `persist`.`enabled` =1";
}
mysql_query($query);
It seems like all you are doing is toggling the column value for all records in the given table. Why even bother reading the value from the database and then doing an update? You can simply do an update right off the bat.
$sql = "UPDATE `somecolumn`.`persist` SET `enabled` = ABS(`enabled` - 1)";
$result = mysql_query($sql);
if (false === $result) { // something went wrong
throw new Exception('Query "'. $sql . '" failed with error: ' . mysql_error());
}
This would flip all 1's to 0's and 0's to 1' without having to do any SELECT at all.
According this: http://php.net/manual/bg/function.mysql-fetch-row.php
You should write this code:
$sql="SELECT enabled FROM somecolumn.persist";
$result = mysql_query($sql);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
$enabled=$row[0];
if ($enabled==0) {
$query="UPDATE `somecolumn`.`persist` SET `enabled` = '1' WHERE `persist`.`enabled` =0";
} else {
$query="UPDATE `somecolumn`.`persist` SET `enabled` = '0' WHERE `persist`.`enabled` =1";
}
mysql_query($query);
Note that msql_ functions are deprecated and will be removed in future versions of php. You should consider changing your code to use PDO or MySQLi libraries.
I'm trying to create an outgoing link click counter. Found some code online and can't understand for the life of me why it does not update the number within the database. What am I doing wrong here?
<?php
$linkid = $_GET["id"];
mysql_query("UPDATE research SET out = out + 1 WHERE id='$linkid'");
$query = "SELECT * FROM research WHERE id='$linkid'";
$result = mysql_query( $query ) or die ("Error in query: $query. ".mysql_error());
while($row = mysql_fetch_row( $result ) ) {
header ("Location:" .$row[2] );
}
?>
Your best bet to understand how this code is working is to learn to check the data like this:
//connect to db here before the rest of your code
if(isset($_GET["id"]){ //only execute if GET is set
$linkid = $_GET["id"];
echo 'GET = '.$linkid.' <br/>'; //check the value to check against your database for testing
mysql_query("UPDATE research SET out= out+1 WHERE id='$linkid'") or die(mysql_error());
//or die helps detect syntax mistakes
if(mysql_affected_rows()){ //if update did occur
$query = "SELECT fieldname FROM research WHERE id='$linkid'";
//no need to use * just select the on fields you need!
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
if(mysql_num_rows($result)>0){ //if a row is found with that id
$row = mysql_fetch_assoc();
echo 'Field Value = '.$row['fieldname'];
//header("location:".$row['fieldname']); - temporarily commented out as headers already sent
} else { echo 'id does not exist in research table'; }
} else { echo 'update did not occur'; }
} else { echo 'GET not set!'; }
I see nothing wrong with your syntax but a few checkers can help explain why it might not be working!
With my script check the outputs and compare it to your database (be sure to check fieldname to the actual name of the field!
It should highlight why it's not working. I've added comments to explain what is going on encase your unfamiliar with some of the function names that i used.