mysql views get decreased - php

I own a image hosting website and I capture image views using php and mysql.
I use the following code to count the views.
include 'mysql.php';
$result = mysql_query("SELECT * FROM DB WHERE ID='$id'");
$row = mysql_fetch_array($result);
$views=$row['views'];
$query = "UPDATE DB SET views=$views+1 WHERE ID='$id'";
$result2 = mysql_query($query);
mysql_close($con);
views is mediumint(9) type field.
I noticed that the views get decreased day by day.can anyone say what is the problem and offer a solution.
Thanks.

You should use this to update instead:
$query = "UPDATE DB SET views=views+1 WHERE ID='$id'";
If a page takes a long time to execute, you can have one query overwrite another. Also using this, you might not need to even run the first query - unless you want other info from it.
The reason you are getting an error is that one script is reading the data and grabbing the value, then updating it - based on the value it is storing - but in the meantime other scripts could be updating the row. You could avoid it by using transactions, but that seems utter overkill for what you are doing.

You need to stop using mysql_* as those functions are deprecated
You don't need to make 2 queries just to increment a field by 1:
$query = "UPDATE DB SET views=views+1 WHERE ID='$id'";
and PDO example:
$db = new PDO('mysql:host=localhost;dbname=mydb;charset=UTF-8', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$stmt = $db->prepare("UPDATE DB SET views=views+1 WHERE ID=:id");
$stmt->execute(array(':id' => $id));
Read more about prepared statements and PDO

Related

Why PDO connection sowing "SQLSTATE[HY000]: General error"?

I am using pdo connection. I am trying to run a delete query but it is showing this message in the browser
*SQLSTATE[HY000]: General error*
Here is my query:
$user_id = $_POST['user_id']; $result = query($conn, "DELETE FROM user WHERE user_id = '$user_id'");
I don't know why happening this. Any kind of help will be appreciated.Thanks
I think there is a query() function does not exists in PHP .. It should be mysql_query or mysqli_query
Using Mysql query is bad because it is depreciated in Updated version of php
$result = mysqli_query($conn, "DELETE FROM user WHERE user_id = '$user_id'");
//So using mysqli :)
$result = mysqli_query($conn, "DELETE FROM user WHERE user_id = '$user_id'");
Per MySQL 5.5.35 source code, sql/sql_prepare.cc:
bool
Reprepare_observer::report_error(THD *thd)
{
/*
This 'error' is purely internal to the server:
- No exception handler is invoked,
- No condition is added in the condition area (warn_list).
The diagnostics area is set to an error status to enforce
that this thread execution stops and returns to the caller,
backtracking all the way to Prepared_statement::execute_loop().
*/
thd->stmt_da->set_error_status(thd, ER_NEED_REPREPARE,
ER(ER_NEED_REPREPARE), "HY000");
m_invalidated= TRUE;
return TRUE;
}
It appears that your error (SQL state HY000) will happen when there is a wrong sequence of prepare/execute statements. Double-check our logic to make sure you are properly using prepared statements, e.g properly fetching all of the results after the call to query() before calling it again.
If you cannot figure it out, isolate the problem to a minimal, complete, and verifiable example (https://stackoverflow.com/help/mcve), and post the code here.
UPDATE:
Does the problem go away (or do you at least get a meaningful error message) if you do
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
prior to the query?

Update database php

mysql_query("UPDATE users SET `test` = '$unicornID' where id='$_SESSION[user_id]' ")
or die(mysql_error());
Now, when user clicks 'add to favorite'-button this line of code updates my database but also deletes all the old data from column test. What command should so that the old data is not deleted?
I think what you may be looking for is an "INSERT" sql query.
It would be something along the lines of;
"INSERT * INTO users WHERE test='$unicornID' and id='$_SESION['user_id']'";
Let me know how it goes. Cheers.
Another tip.
Use PDO with prepared statements:
$pdo = new PDO(sprintf('mysql:host=%s;dbname=%s', HOST, DATABASE), USER, PASSWORD);
And to insert something:
$params = array(':unicornID' => $unicornID, ':id' => $_SESSION['user_id']);
$stmt = $pdo->prepare("INSERT * INTO users WHERE test=:unicornID and id=:id");
$stmt->execute($params);
The old mysql(_query) commands are old and very vulnerable, PDO isn't as vulnerable.
The advantage of prepared statements are mainly that you can't inject via your variables some sql code.
Hope you understood my and my code
"Update" means that the old data row is changed; if you want to keep it, you have to insert a new one. In this case I think that you should copy the row (which may be done using "insert... select...") and then update the newly inserted line.

Php MYSQL query problems

Okay so this problem is really boggeling my mind... I have a MYSQL query I want to make so that my php program can access and update the database with lat and long coordinates of a user and im getting issues...
This is non working code:
$currUsername = strtolower($_SESSION['username']);
$sql= "UPDATE users SET pos_Lat=$latitude, pos_Long=$longitude WHERE username=$currUsername";
$result = mysql_query($sql, $link);
The working code
$currUsername = "email_that_is_returned"
$sql= "UPDATE users SET pos_Lat=$latitude, pos_Long=$longitude WHERE username=$currUsername";
$result = mysql_query($sql, $link);
Is this because session returns data that is not able to be placed inside a query?
Check whether the session was started or not. if not started then add the following code to your page and then check its working or not.. i thing your session does not return any value.. so start session by using the code session_start();
session_start();
$currUsername = strtolower($_SESSION['username']);
$sql= "UPDATE users SET pos_Lat=$latitude, pos_Long=$longitude WHERE username=$currUsername";
$result = mysql_query($sql, $link);
You can check what type of data it is returning.
print $_SESSION['username'].
Also there is a chance to break the SQL query if the $_SESSION['username'] returns data with spaces. Make sure the SQL query not failing even if the $_SESSION['username'] contains spaces and singlequotes etc..

Is it possible to run multiple update queries in one using Joomla?

I want to run many SQL update queries at one time using JOOMLA 2.5. Below my code:
require_once '../includes/framework.php';
$query = "UPDATE #__mytable SET myfield='value' where id=1; UPDATE #__mytable SET
myfield='value' where id=2; UPDATE #__mytable SET myfield='value' where id=3;";
$db = JFactory::getDbo();
$db->setQuery($query);
$db->query();
But it shows me a syntax error. I tried to test directly in MYSQL and it works.
PHP does not allow multiple queries by default. You can force it to do so by adding a parameter to mysql_connect, but I wouldn't recommend it (it opens huge security holes for SQL injections).
I don't know how JFactory handles this, but I would be surprised if it were different.
More infos about it: http://de3.php.net/manual/en/function.mysql-query.php#91669
You must use JDatabaseDriver::splitSql() to
split a string of multiple queries into an array of individual queries, and run them once at a time.
This is how the internal extensions installer works.
Don't worry about comments, they will be stripped off.
$sql = "UPDATE #__mytable SET myfield='value' where id=1; UPDATE #__mytable SET myfield='value' where id=2; UPDATE #__mytable SET myfield='value' where id=3;";
$db = JFactory::getDbo();
$queries = JDatabaseDriver::splitSql($sql);
foreach ($queries as $query)
{
try
{
$db->setQuery($query)->execute();
}
catch (JDatabaseExceptionExecuting $e)
{
...
}
}

PHP MYSQL: Correct Code to Increment a views column every time a page is loaded in the browser

I am trying to create a "views" system on my books website.
I have the following tables with the following columns:
Books
-bookid
-bookname
-authorid
-views
my webpage is set up to display a book based on the $_GET['bookid'] variable and I want to add 1 (increment the views column by one for that particular book)
I tried using the following code but it didn't update my table:
<?php $sql = "UPDATE `books` \n" . "SET views = views+1 WHERE" . $_GET['bookid'] .= "bookid"; ?>
ALSO: I used dreamweaver to run the recordset query) so maybe something is different.
Please Help!
Sidenote: Can you please recommend a good book/video or written tutorial to learn php and mysql for absolute beginners like my self!
This is important: don't include $_GET paramaters directly in your SQL query.
This makes your website vulnerable to an SQL Injection attack. Sanatise your inputs by using:
$book_id = mysql_real_escape_string($_GET['book_id']); // If it is a string
$book_id = intval($_GET['book_id']); // It it is an integer
// Assuming it is an integer
$sql = "UPDATE books SET views = views+1 WHERE bookid = $book_id";
You obviously need to execute that query, are you doing that?
$user="username";
$password="password";
$database="database";
mysql_connect(localhost,$user,$password);
mysql_select_db($database) or die( "Unable to select database");
mysql_query($sql);
mysql_close();
EDIT:
Also, just a tip, since you're using $_GET you should be executing something like yourscript.php?book_id=12345, is that what you're doing?
you've already found some of the best ways to learn PHP: writing code and coming here when you don't know further :) (don't have a real good tutorial on my hands beyond that ;)
As for your question:
check the value of $_GET['bookid']
check the value of $sql
if all looks as intended, run the query directly
oh wait.
you're not actually executing the sql in your code, just generating a string with the query. you need to open a connection etc, or are you doing that and leaving it out here?
Your query looks slightly off. Try this:
$sql = 'UPDATE books SET views = views+1 WHERE bookid = ' . intval($_GET['book_id']);

Categories