mysql UPDATE code dont work :(( - php

I have a like button on my site http://zabavajsa.eu/new/ .
When you click on the button, it shoud add +1 like to the database and it doesn't work.
Here is my code:
<form method='post'>
<li>
<button class='like' name='like' value='48'>Like</button>
</li>
</form>
<?php
if(isset($_POST['like'])) {
$id = $_POST['like'];
require('db.php');
$resultiiik = $mysql->query("SELECT * FROM fotka WHERE id='{$id}'");
$p = $resultiiik->fetch_assoc();
$pocet = $p[like];
$pocet = $pocet +1;
$mysql->query("UPDATE fotka SET like='{$pocet}' WHERE id='{$id}'") or die ('This always write to me -.-');
}
?>

Firstly, this
<button class='like' name='like' value='48'>Like</button>
it needs a "type", let's use a "submit" type
<button class='like' name='like' value='48' type='submit'>Like</button>
then the word like is a MySQL reserved word which needs to be wrapped in ticks
SET `like`
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
LIKE is used in string comparisons and pattern matching
http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html
http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html
Therefore it's best to stay away from using reserved words. You could use the word "likes" instead and won't require the column to be escaped, or do as above and wrap it in backticks.
You're also not getting MySQL to signal the proper errors with
or die ('This always write to me -.-')
use
or die(mysqli_error($mysql))
or
die('There was an error running the query [' . $mysql->error . ']')
Which would have triggered something like:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'like
Edit:
As stated in comments, your code is vulnerable to SQL injection.
Use prepared statements, or PDO with prepared statements, they're much safer.

Additionally to #Fred -ii- 2 more bugs:
$pocet = $p[like];
like is a constant, but since you never define a constant named 'like' php will just treat it as string and print a notice if they are enabled. You should use $pocet = $p['like']; instead of $pocet = $p[like];
And: You don't need to fetch the value just to increment and update it. Your Database can do the work for you:
UPDATE fotka SET `like`=`like`+1 WHERE id='{$id}'

Related

1064 error, Not sure what the issue is

I keep getting this error when submitting. I have checked my form 10x and I cannot figure out what is wrong with it.
Here is the error
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE order_num = '5293528'' at line 1
Here is the form code
public function next()
{
try
{
if(isset($_POST['giventoatpdate']))
{
$update = trim($_POST['update']);
$orders = $_SESSION['order_nums'];
$st=$this->db->prepare("INSERT INTO `orders` (giventoatpdate) VALUES (:upd) WHERE order_num = :orderr");
$st->bindparam(":upd", $update);
$st->bindparam(":orderr", $orders);
$st->execute();
return $st;
}
$order = $_GET['uid'];
$stmt=$this->db->prepare("SELECT * FROM orders WHERE order_num = :order");
$stmt->execute(array(":order"=>$order));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
if($row['giventoatpdate'] = ' ')
{
echo
"
<form name='atpdate' method='POST'>
Date Sent to clown?
<br>
<input type='text' name='update'>
<br>
<input type='submit' name='giventoatpdate'>
</form>
";
}
Everything else is working fine. It gives me this error when I hit submit.
Seeing somebody popped in an answer...
It's because INSERT doesn't have a WHERE clause.
Now read the manual http://dev.mysql.com/doc/en/insert.html
INSERT ... ON DUPLICATE KEY UPDATE does.
http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html
Or, you may have intended to do an UPDATE. http://dev.mysql.com/doc/en/update.html
Seeing $update = trim($_POST['update']); the operative word being "update" in the POST array, I'm thinking you want to do an UPDATE here rather than an INSERT, since you are dealing with orders taken from your site.
So, you have a few choices here.
If it's an UPDATE, your query would read as:
UPDATE `orders`
SET giventoatpdate = :upd
WHERE order_num = :orderr
Check for errors:
http://php.net/manual/en/pdo.error-handling.php
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Footnotes:
Seeing if($row['giventoatpdate'] = ' ') you do realize that this checks for a "space" rather than if($row['giventoatpdate'] = '') to check if it's "empty".
You're also "assigning" rather than doing a "comparison" here which should read as:
if($row['giventoatpdate'] == '')
If you're checking for empty'ness, then remove the space in there, or you can do
if(empty($row['giventoatpdate']))
References:
http://php.net/manual/en/language.operators.assignment.php
http://php.net/manual/en/language.operators.comparison.php
http://php.net/manual/en/function.empty.php
INSERT doesn't have WHERE operator.
You need to change query to something like this:
UPDATE myTable SET my_field = :new_value WHERE my_another_filed = :another_value_or_row_id

Selecting and Displaying mysql data through hidden form

I'm having trouble displaying my selected data through MYsql. I have values already stored in the fields in my database and when the user clicks the submit button and the review of the selected movie should populate but its not.
Here is my code for the form in php.
echo "<tr><td>".$utitle."</td><td>".$ucategory."</td><td>".$ulength."</td><td>Thumbs up</td>t<td></td>";
echo '<form action = "videos.php" method="POST">';
echo "<td><input type='hidden' name='read' value=".$uid."><input type='submit' value='Read the Review' name='read'></td></tr></form>";
And here is my code when the button is clicked.
if(isset($_POST['read'])){
$readReview = "SELECT Review FROM MyVideos WHERE id='$_POST[read]'";
$read = $con->query($readReview);
if($read->num_rows>0){
while($row=$read->fetch_assoc()){
echo "Review:".$row['Review']."<br/>";
}
}
$read->close();
};
Thanks. Any help is greatly appreciated.
Putting my comment to an answer.
Both your hidden input and submit button bear the same name attribute. I'd call that a conflict. Plus, it's discarding the first attribute, being the hidden one.
Also, your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
$id = mysqli_real_escape_string($con, $_POST['read']);
$readReview = "SELECT Review FROM MyVideos WHERE id='id'";
Sidenote: $_POST['read'] will need to be changed to the name attribute you'd of given to the hidden input.
Yet, prepared statements are the way to go here.
Remember to rename your hidden input to something else of your choice.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
References:
http://php.net/manual/en/mysqli.real-escape-string.php
http://php.net/manual/en/function.error-reporting.php
Object oriented style
string mysqli::escape_string ( string $escapestr )
string mysqli::real_escape_string ( string $escapestr )
Procedural style
string mysqli_real_escape_string ( mysqli $link , string $escapestr )
In the code, this line:
$readReview = "SELECT Review FROM MyVideos WHERE id='$_POST[read]'";
the single quotes are missing around read. The single quotes appear as we expect them here:
if(isset($_POST['read'])){
^ ^
But beyond adding single quotes, the code is vulnerable to SQL Injection.
Use prepared statement with bind placeholder. Assuming that id column in MyVideos is character type:
if(isset($_POST['read'])){
$readReview = 'SELECT Review FROM MyVideos WHERE id=?';
$sth=$con->prepare($readReview);
$sth->bind_param('s',$_POST['read']);
$sth->execute();
$sth->bind_result($review);
while($sth->fetch()){
echo "Review:".htmlentities($review)."<br/>";
}
$sth->close();
}
To make the pattern more clear, the code example above doesn't check the return from the prepare or execute. We'd really want to check if the return from prepare is FALSE, we don't want to call bind_param or execute on that.
If id column is integer type, then replace 's' with 'i' (as the first argument in the bind_param.
The use of htmlentities assumes that the contents of the Review column does not contain any HTML markup that should not be escaped/encoded.
submit and hidden field is same (not sure check it by changing)
change query:-
$readReview = "SELECT Review FROM MyVideos WHERE id='". $_POST[read] . "'"; // If id is varchar type or
$readReview = "SELECT Review FROM MyVideos WHERE id=$_POST[read]"; // If numric type

Insert, Update, Create Table, queries not working in wampserver

I've been using wampserver for a php project, but DML queries are not working for me. Here is some test code I've been using
$query='insert into register(first_name) values("swagmaster")';
echo($query);
$query = mysqli_real_escape_string($connection,$query);
echo"<br>$query";
if(mysqli_real_query($connection,"'".$query."'")===TRUE)
{
echo"woohoo!";
}
else
{
echo"query failed";
}
echo(mysqli_error($connection));
I get the following output when i run this:
insert into register(first_name) values("swagmaster")
insert into register(first_name) values(\"swagmaster\") query failed
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''insert into register(first_name) values(\"swagmaster\")'' at line 1
However, a select statement works fine. I suspect the issue is in mysql settings. Any suggestions?
UPDATE:
Using a combination of your tips, the query is now working. Thank you all!
Please try this query
$query = "INSERT INTO `register` SET `fieldname`='{$vaue}',`field2`='{$value2}'";
Change the query from
$query='insert into register(first_name) values("swagmaster")';
to
$query="insert into register(first_name) values('swagmaster')";
Also as Fred-ii said you dont need to add ' here
if(mysqli_real_query($connection,"'".$query."'")===TRUE)
change to
if(mysqli_real_query($connection,$query)===TRUE)
You used
$query = mysqli_real_escape_string($connection,$query);
But this escaped all quotes in query. This is incorrect. For protected fro SQL injection you should use escape function only to value instead query.
For your example you not need this string.
But if you use variables then you should use it
$value = "swagmaster";
$value = mysqli_real_escape_string($value);
$query='insert into register(first_name) values("' . $value . '")';
In $query is already correct query. And add quotes is incorrect. Just use
if(mysqli_real_query($connection, $query)===TRUE)

How to update a specific data of a table?

I am making a likes/dislikes thing in php & html. So, since it uses likes for each blog, I use the blog ID. I would like to know how I could update the "likes" in the table, but only update the "likes" of the specific row using it's id. Here is the php script:
<?php
require 'init.php';
$rating = $_GET['rating'];
$postid = $_GET['id'];
if ($rating = "like") {
$sql = "
";
}
if ($rating = "dislike") {
$sql = "
UPDATE
posts
SET
dislikes = dislikes+1
WHERE
id = $postid
";
}
?>
The update query does not seem to be the problem here, the main problem is your if statement, where you are not using comparison operator but are using assignment operator.
The statement: if ($rating = "like") assigns value "like" to the variable $rating, it does not compare $rating against value "like", which is what I think you want it to do.
There are few other "major" issues to note is that you are wide open for SQL Injection attacks. Since you mentioned that you are using mysql_ functions in your comment, you at least want to make use of mysql_real_escape_string function. e.g.
$rating = mysql_real_escape_string($_GET['rating'], $con); // assuming $con is your MySQL Connection
$postid = mysql_real_escape_string($_GET['id'], $con);
Another equally important point to note is that mysql_ functions are deprecated. You definitely should consider using either mysqli or pdo.
Third and final point to note is that if your rating is "like" then the query is empty. Hopefully you are checking for emptyness before calling mysql_query, which is not shown here.

How do I load data to textbox from mysql

I have (html)
input type="text" name="input"
textarea name="output"
Next, I have some table, first name and last name. When I inserting first name in input area I would like to show last name in output area.
Below PHP query doesn't working.
$input = $_POST['input'];
$select = mysql_query("SELECT first_name FROM table WHERE input=$input");
$req = mysql_fetch_array($select);
You are missing quotes around the value you are inserting. Use
input='$input'
You are not doing any error checking in your query, so in cases like this, things will break silently. To do proper error checking and get verbose messages check out the manual on mysql_query() or in this reference question.
Also, the code you show is vulnerable to SQL injection. Use the proper sanitation method of your library (in this case, mysql_real_escape_string()) for all the string data you insert, or switch to PDO and prepared statements.
Example using your current code:
# Escape string input
$input = mysql_real_escape_string($_POST['input']);
# Run query
$select = mysql_query("SELECT first_name FROM table WHERE input='$input'");
# Check for errors
if (!$select)
{ trigger_error("mySQL error: ".mysql_error());
die();
}
There are a number of problems.
First, your table is probably not called table but something else. If it is in fact for some reason called table then you need to surrounded it in backticks because table is a reserved word. But it would be much better to change the name to not be a reserved word.
Second, you are also not correctly escaping the user input data. You could consider using mysql_real_escape_string for this purpose.
$input = mysql_real_escape_string($_POST['input']);
Finally, you should quote the user text in the SQL string:
$select = mysql_query("SELECT first_name FROM `table` WHERE input='$input'");
Alternatively you could use a parameterized query.
Hope this helps
//PHP
$firstname='';
$lastname='';
if(isset($_POST['go']))
{
$firstname=$_POST['firstname'];
$records = mysql_query("SELECT last_name FROM
table WHERE firstname='$firstname'");
if(mysql_num_rows ==1)
{
while($row=mysql_fetch_array($records))
{
$lastname=$row['last_name'];
}
}
}
//HTML
echo"<form method='post' >
echo" <input type='text' name='firstname' value='$firstname' />";
echo"<input type='submit' value='Go' /> ";
echo" <input type="text" name='lastname' value='$lastname' />";
echo"</form>";
as you said you want to get last_name depending on first_name your query should look something like
$input = $_POST['input'];
$select = mysql_query("SELECT last_name FROM table WHERE first_name = '".$input."'");
$req = mysql_fetch_array($select);
try to concat variables in strings because its faster than substitution.

Categories