How to update a specific data of a table? - php

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.

Related

SQL database not updating data in PHP [duplicate]

This question already has answers here:
How to view query error in PDO PHP
(5 answers)
Closed 2 years ago.
I'm trying to update some data from my database but nothing I've tried/found has been of any success to me. There are no errors or anything, literally nothing happens. The page reloads but it does not store anything into the database. How can I fix this problem?
The code:
function AddToBook() {
$get_post_id = filter_var(htmlentities($_GET['pid']), FILTER_SANITIZE_NUMBER_INT);
$book_id = filter_var(htmlentities($_GET['bid']), FILTER_SANITIZE_NUMBER_INT);
$get_episodes = filter_var(htmlentities($_GET['ep']), FILTER_SANITIZE_NUMBER_INT);
$episode = $get_episodes + 1;
// Insert book data into wpost
$odb = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$updatePostRecord = "UPDATE wpost SET book_id=:book_id, episode_number=:episode WHERE id=:get_post_id";
$UpdatePost = $odb->prepare($updatePostRecord);
$UpdatePost->bindParam(':book_id',$book_id,PDO::PARAM_INT);
$UpdatePost->bindParam(':episode',$episode,PDO::PARAM_INT);
$UpdatePost->bindParam(':get_post_id',$get_post_id,PDO::PARAM_INT);
$UpdatePost->execute();
// Insert post data into books
$updateBookRecord = "UPDATE books SET episodes='$episode' WHERE id='$book_id'";
$UpdateBook = $conn->prepare($updateBookRecord);
$UpdateBook->execute();
}
You want to use the PDO class that you have defined there instead of $conn (that is not defined), might as well put the variables into brackets just to make sure they are interpreted correctly, if you use a string literal.
$updateBookRecord = "UPDATE books SET episodes='{$episode}' WHERE id='{$book_id}'";
$UpdateBook = $obd->prepare($updateBookRecord);
$UpdateBook->execute();
Also, as it stand right now this is not a proper prepared statement. You should use bindParam function like on the initial UpdatePost.
Here is how it would look as a proper prepared statement.
$updateBookRecord = "UPDATE books SET episodes=:episode WHERE id=:book_id";
$UpdateBook = $obd->prepare($updateBookRecord);
$UpdateBook->bindParam(':episode',$episode,PDO::PARAM_INT);
$UpdateBook->bindParam(':book_id',$book_id,PDO::PARAM_INT);
$UpdateBook->execute();
An update can successfully update 0 rows. I would triple check your WHERE clause to see if it is actually trying to match existing rows.
When you use single quotes '' with variable, php understand it as a string not variable. so you might want to change your update statement to
$updateBookRecord = "UPDATE books SET episodes = $episode WHERE id= $book_id ";
or alternatively
$updateBookRecord = "UPDATE books SET episodes = ". $episode . " WHERE id= ".$book_id;
However this is not the standard way to do things, and invite sql injections, you better use PDO or other mechanism to make it more secure. https://www.w3schools.com/sql/sql_injection.asp

Seemingly identical sql queries in php, but one inserts an extra row

I generate the below query in two ways, but use the same function to insert into the database:
INSERT INTO person VALUES('','john', 'smith','new york', 'NY', '123456');
The below method results in CORRECT inserts, with no extra blank row in the sql database
foreach($_POST as $item)
$statement .= "'$item', ";
$size = count($statement);
$statement = substr($statement, 0, $size-3);
$statement .= ");";
The code below should be generating an identical query to the one above (they echo identically), but when I use it, an extra blank row (with an id) is inserted into the database, after the correct row with data. so two rows are inserted each time.
$mytest = "INSERT INTO person VALUES('','$_POST[name]', '$_POST[address]','$_POST[city]', '$_POST[state]', '$_POST[zip]');";
Because I need to run validations on posted items from the form, and need to do some manipulations before storing it into the database, I need to be able to use the second query method.
I can't understand how the two could be different. I'm using the exact same functions to connect and insert into the database, so the problem can't be there.
below is my insert function for reference:
function do_insertion($query) {
$db = get_db_connection();
if(!($result = mysqli_query($db, $query))) {
#die('SQL ERROR: '. mysqli_error($db));
write_error_page(mysqli_error($db));
} #end if
}
Thank you for any insite/help on this.
Using your $_POST directly in your query is opening you up to a lot of bad things, it's just bad practice. You should at least do something to clean your data before going to your database.
The $_POST variable often times can contain additional values depending on the browser, form submit. Have you tried doing a null/empty check in your foreach?
!~ Pseudo Code DO NOT USE IN PRODUCTION ~!
foreach($_POST as $item)
{
if(isset($item) && $item != "")
{
$statement .= "'$item', ";
$size = count($statement);
$statement = substr($statement, 0, $size-3);
$statement .= ");";
}
}
Please read #tadman's comment about using bind_param and protecting yourself against SQL injection. For the sake of answering your question it's likely your $_POST contains empty data that is being put into your query and resulting in the added row.
as #yycdev stated, you are in risk of SQL injection. Start by reading this and rewrite your code by proper use of protecting your database. SQL injection is not fun and will produce many bugs.

php add column with specific id and how to echo result of exact id

id 1stPayment 2ndPayment 3rdPayment 4thPayment Tuition
8 0 200 2000 2000 9000
8 2000 0 0 0 0
9 0 0 0 0 1000
10 1 0 0 0 0
i want to add all the tuition of id-8 and echo the result of the sum of the tuition. how can i sum all the tuition with out adding the tuition of other id's. the table name is "students_payments"... "i also want to echo the tuition of an id in its own page, like when i access the account of id-8 it shows the sum of its tuition. :D
i have this code, but when i access the account of id-9 and id-10 it shows the added value of all the tuition. tnx in advanced.. :D
<?php
include("confstudents.php");
$id = $_GET['id'];
$result = mysql_query("select * from student_payments where id='$id' ");
while ($res = mysql_fetch_assoc($result)) {
$result = mysql_query("SELECT SUM(Tuition) FROM student_payments");
while ($row = mysql_fetch_assoc($result)) {
$TT = $row['SUM(Tuition)'];
echo "Php $TT";
}
}
?>
You query should be
SELECT SUM(Tuition) as TotalTuition FROM student_payments WHERE id='$id' GROUP BY id
Then you can just echo TotalTuition.
Warning
your code is vulnerable to sql injection you need to escape all get and post and the better approach will be using Prepared statement
Good Read
How to prevent SQL injection in PHP?
Are PDO prepared statements sufficient to prevent SQL injection?
Note
The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, is officially deprecated as of PHP v5.5.0 and will be removed in the future. So use either PDO or MySQLi
Good read
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
PDO Tutorial for MySQL Developers
Pdo Tutorial For Beginners
A few things about your code:
Always cast data to what you expect them to be (in the case of your id, that should be an integer).
Never put any unescaped strings into SQL queries. You never know what people type into your applications input fields. In this case I don't use mysql_escape, as the id was casted to integer, which is of no harm to the query.
Never (!) use mysql_query in a loop. You never need it and it will always slow down your application without providing any use.
If your database expects an integer, then give it an integer and not a string. id is expected to be an integer, but '$id' will always be a string. Unfortunately MySQL silently tries to cast this to integer instead of complaining...
As I am very picky: id is an abbreviation for identifier, which in turn means, that you can identify something by it. Resulting from that, an identifier must always be unique. I hope you chose it merely to explain your question.
Use ' instead of " for strings wherever you can. This will keep the PHP parser from trying to interpret the string. Makes your code a little more save and faster.
Though mysql_* functions are deprecated, I have only extended your code. So for an answer to your question see the code below.
<?php
include("confstudents.php");
$id = (int)$_GET['id']; // cast to int to prevent SQL injection; if you can't do that (e.g. it is a string), use mysql_escape()
if ($id <= 0) { // check if the id is at all valid and break here if it isn't
die('Invalid ID');
}
$result = mysql_query('SELECT SUM(tuition) sum_tuition FROM student_payments WHERE id = ' . $id);
if ($result === FALSE) { // Check if the statement was able be processed
die('Error in SQL statement'); // break here, if it wasn't
}
$res = mysql_fetch_assoc($result); // with the SQL above, there's always exactly one row in the result
echo 'Php ' . $res['sum_tuition'];
?>
You can add some more debugging code such as mysql_error() to find errors in your SQL statements. But don't display that to your users. They might know, how use it for exploiting your application...
<?php
include("confstudents.php");
$id = $_GET['id'];
$result = mysql_query("SELECT SUM(Tuition) FROM student_payments where id='$id'");
while ($row = mysql_fetch_array($result)) {
$TT = $row['SUM(Tuition)'];
echo "$TT";
}
?>

How do I check to see if "title" exist in mysql database

First stackoverflow question ever woot!
FUNCTION : To check and see if data exist before allowing INSERT - trying to make it non-case senstive and as open as possbile since the title I'm trying to avoid a dup is only for a specifc artistid (explained below)
The table row structure is as follows
id (auto_increment)
artist (specfic id number only assigned to that artist)
title (what we are trying to make sure we don't get a dupicate only for this artist
ISSUE : Does not get needed data from database or post defined error, might be wrong in if statement = unknown exactly what is issue
$_POST['title']; is passed from user input
if (isset($submit)) {
$date = date("Ymd");
$cleanTitle = $_POST['title'];
$querytitle = mysql_real_escape_string($_POST['title']);
$queryalbum = mysql_real_escape_string($_POST['album']);
// Check to see if Title exist for specfic Artist
$checkTitle = mysql_query("SELECT * from lyrics WHERE artist = '$artist'");
if (!$checkTitle) {
die('Query Failed');
}
if ($checkTitle == $cleanTitle) {
// do whatever
}
print_r($checkTitle); // the data returned from the query
UPDATE : INSERT IGNORE wouldn't work sicne I'm inserting the data via $artist and need to check and see if title exist on that artist first. or i might be wrong. i'm unsure on how to do it
$artist is a specfic ID number defined higher in the code
Your code was incorrect, but this should work:
if (isset($submit)) {
$date = date("Ymd");
$cleanTitle = $_POST['title'];
$querytitle = mysql_real_escape_string($_POST['title']);
$queryalbum = mysql_real_escape_string($_POST['album']);
// !!! $artist is not actually set anywhere here..
$checkTitle = mysql_query("SELECT * from lyrics WHERE artist = '$artist'");
if (!$checkTitle) {
die('Query Failed');
}
/* now that you have run the query, you need to get the result: */
// (This is assuming your query only returns one result)//
$result = mysql_fetch_array($checkTitle);
// now check the value for 'title'
if ($result['title'] == $cleanTitle) {
// do whatever
}
print_r($result); // the data returned from the query
}
You were running the query, but you were not getting the results of the query. You use mysql_fetch_array() to get the results. To get the results of multiple entries, you can use the following:
// will print the 'title' for each results
while ($row = mysql_fetch_array($checkTitle)) {
echo $row['title'];
}
Now with all of that said, you should know that mysql_* is going through a deprecation process and should be replaced with mysqli or PDO. Please read the following:
Please, don't use mysql_* functions in new code. They are no longer maintained and the
deprecation process has begun on it. See the
red box? Learn about prepared statements instead, and use
PDO or MySQLi - this article will help you decide which. If you choose
PDO, here is a good tutorial.
Here is very simple code to check if that title has any post (you may already know, that at first, the file needs to require wp-blog-header.php).
$title = 'mytitlee';
global $wpdb;
$id_ofpost_name = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = $title");
$id_ofpost_title = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_title = $title");
if ($id_ofpost_name || $id_ofpost_title) {echo 'Exists, here is the id:'.$id_ofpost_title.$id_ofpost_name;}
else {echo 'post wasnt found';}

query two tables in one mysql query

im having trouble getting data from two seperate tables
so far i have this
<?
include('config.php');
$xid = $_GET['xid'];
$result = mysql_query("SELECT * FROM `config`") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$result = mysql_query("SELECT * FROM `utinfo` WHERE `xid` = $xid") or trigger_error(mysql_error());
while($row2 = mysql_fetch_array($result)){
foreach($row2 AS $key => $value) { $row2[$key] = stripslashes($value); }
$un = urldecode($row2['un']);
};
switch ($row['module'])
{
case 1:
echo "Function 1 for user $uid on account $un";
break;
case 2:
echo "Function 2 for user $uid on account $un";
break;
case 3:
echo "Function 3 for user $uid on account $un";
break;
default:
echo "No module defined.";
};
};
?>
The config table config has the row named modules, and its populated by 2 entries, one of which is 1, the other 3. So i should be seeing case 1 and then case 3. But all im getting is the default echo.
(This is not an answer to the OP, but something you really should care about, so I think it's worth writting it)
It seems there is a enormous SQL-injection in your code.
The normal way of calling your page would be with something like "xid=5" in the URL, to get informations of user #5.
Now, suppose someone give "xid=5 or 1=1". The resulting query would be :
SELECT * FROM `utinfo` WHERE `xid` = 5 or 1=1
The condition is always true ; you'd get informations of ALL users as an output, as you iterate through the resultset.
Another possibility : "xid=5; delete from utinfo;" ; which would give this query :
SELECT * FROM `utinfo` WHERE `xid` = 5; delete from utinfo;
That would empty your table :-(
You must always escape / check / sanitize / whatever you data before putting them in a SQL query, especially (but not only) if they come from a user of the application.
For strings, see the mysql_real_escape_string function.
For data that sould be integers, you could use intval (worst case, if data was not valid, you'll get 0, which might get no result from the DB, but, at least, won't break it ^^ )
Another solution would be to use prepared statements ; but those are not available with mysql_* function : you have to switch to either
mysqli_*
or PDO
Anyway, for a new application, you shouldn't use mysql_* : it is old, and doesn't get new functionnalities / improvements that mysqli and PDO get...
stripslashes() is used on strings. Your case values are integers. It seems like you have a type mismatch here?
Why are you not using PDO? You should really standardis on PDO if you can.
Table names in SQL select should not be quoted.
You should consider using prepared statements in order to avoid SQL Injection and then you don't have to worry about having to quote your paramaters
The first answer is probably correct regarding type mismatches, you should be able to fix the issue by using the following code:
switch ((integer) $row['module'])
See the following:
http://us.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting
Alternatively, you could try this:
settype($row['module'], "integer");
switch ($row['module'])
See:
http://us.php.net/manual/en/function.settype.php
I would also suggest echo'ing the value of $row['module'] onto the page just to check that it is indeed an integer.

Categories