PHP posting a variable in a variable using mysql - php

I need to use the number of the district to be the tail end of my variable. Example $publish_page_ADD THE DISTRICT NUMBER
I am grabbing the $district_num from my url which I've verified with echo
Here is what I've tried
$district_num = $_REQUEST['district_num']; // from url and works
$publish_page_.''.$district_num = $district_var['publish_page_'.$district_num.'']; //this does not work
$publish_page_.''.$district_num = addslashes($_POST['publish_page_'.$district_num.'']); //this does not work
$sql = "UPDATE districts SET
publish_page_$district_num = '$publish_page_$district_num' //this does not work and throws error "can not find publish_page_ in field list
WHERE district_num ='$district_num'"; //this works when the above code is removed
Follow up on corrected code... Thank You #cale_b and #Bill Karwin
$district_num = (int) $_REQUEST['district_num'];
$$publish_page = "publish_page_{$district_num}";
$$publish_page = $district_var[ "publish_page_{$district_num}"];
if (isset($_POST['submitok'])):
$$publish_page = addslashes($_POST[$publish_page]);
$sql = "UPDATE districts SET
publish_page_{$district_num} = '$publish_page'
WHERE district_num ='$district_num'";

If you want to learn about PHP's variable variables, it's in the manual (I linked to it). But you actually don't need it in your case.
Be careful about SQL injection. Your code is vulnerable to it.
Since you're using input to form a SQL column name, you can't use SQL query parameters to solve it. But you can cast the input to an integer, which will protect against SQL injection in this case.
$district_num = (int) $_REQUEST['district_num'];
$publish_page_col = "publish_page_{$district_num}";
The above is safe because the (int) casting makes sure the num variable is only numeric. It isn't possible for it to contain any characters like ' or \ that could cause an SQL injection vulnerability.
For the other dynamic values, use query parameters.
$publish_page_value = $_REQUEST["publish_page_4{$district_num}"];
$sql = "UPDATE districts SET
`$publish_page_col` = ?
WHERE district_num = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([ $publish_page_value, $district_num ]);
As #cale_b comments below, you should understand that in PHP, variables can be expanded inside double-quoted strings. See http://php.net/manual/en/language.types.string.php#language.types.string.parsing for details on that.

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

Q: PostGreSQL How to Pass POST information in a SQL command more efficiently

I have a page that brings up a users information and the fields can be modified and updated through a form. Except I'm having some issues with having my form update the database. When I change the update query by hardcoding it works perfectly fine. Except when I pass the value through POST it doesn't work at all.
if (isset($_POST['new']))
{
$result1 = pg_query($db,
"UPDATE supplies.user SET
id = '$_POST[id_updated]',
name = '$_POST[name_updated]',
department = '$_POST[department_updated]',
email = '$_POST[email_updated]',
access = '$_POST[access_updated]'
where id = '$_POST[id_updated]'");
if (!$result1)
{
echo "Update failed!!";
} else
{
echo "Update successful;";
}
I did a vardump as an example early to see the values coming through and got the appropriate values but I'm surprised that I get an error that the update fails since technically the values are the same just not being hardcoded..
UPDATE supplies.user SET name = 'Drake Bell', department = 'bobdole',
email = 'blah#blah.com', access = 'N' where id = 1
I also based the form on this link here for guidance since I couldn't find much about PostGres Online
Guide
Try dumping the query after the interpolation should have happened and see what query you're sending to postgres.
Better yet, use a prepared statement and you don't have to do variable interpolation at all!
Do not EVER use data coming from external sources to build an SQL query without proper escaping and/or checking. You're opening the door to SQL injections.
You should use PDO, or at the very least pg_query_params instead of pg_query (did you not see the big red box in the manual page of pg_query?):
$result1 = pg_query($db,
"UPDATE supplies.user SET
id = $1,
name = $2,
department = $3,
email = $4,
access = $5
WHERE id = $6",
array(
$_POST[id_updated],
$_POST[name_updated],
$_POST[department_updated],
$_POST[email_updated],
$_POST[access_updated],
$_POST[id_updated]));
Also, when something goes wrong, log the error (pg_last_error()).
By the way, UPDATE whatever SET id = some_id WHERE id = some_id is either not really useful or not what you want to do.

Unassigned php variable in WHERE clause of mysql query

I have a query with php variables in WHERE clause. But it does not return results if the variables are unassigned.
$customer = isset($_REQUEST['customer'])?$_REQUEST['customer']:'';
$territory = isset($_REQUEST['territory'])?$_REQUEST['territory']:'';
$status = isset($_REQUEST['status'])?$_REQUEST['status']:'';
$getOrder = "SELECT * FROM order WHERE Customer = '$customer' AND Territory = '$territory' AND Status = '$status'";
$getOrderQuery = mysql_query($getOrder);
while($iRow = mysql_fetch_array($getOrderQuery))
{ .... }
If the three variables are assigned, it returns results. What do I need to do so that the query will return results even the variables are empty?
I can't comment on your post but I can leave an answer.
Try to echo $getOrder;
make sure the variables have what you expect and then take the query and execute it directly on the database using MySQL client or phpMyAdmin.
Also, you should escape your variables as you are valuable to a SQL injection attack. I like to use PDO API.
you can also try this based on the comment below
SELECT * FROM order
WHERE IFNULL(Customer, '') IN('$customer', '') AND IFNULL(Territory,'') IN('$territory','') AND IFNULL(Status, '') IN('$status','')";

php save html-code in phpmyadmin

I have a little problem to save html-code in phpmyadmin.
Thats the html-code ($html_txt) which I would like to save in the sql-table. I get the code from an other sql-query.
An günstigen Tagen "Paradies" ist es dienlich.
Test/Test<br /><br />"Test"
And that is my query.
$id = 1;
$html = "'".$html_txt"'";
$sql = 'UPDATE table SET text = '.$html_txt.' WHERE id = '.$id.'';
That does not work. Any idea? I tried it also like this:
$id = 1;
$html_txt;
$sql = 'UPDATE table SET text = '.$html_txt.' WHERE id = '.$id.'';
You must escape the string statements before querying. Your query should be like the following:
$con = mysqli_connect("localhost","user","password","db");
$id = mysqli_real_escape_string($con, $id);
$html_txt = mysqli_real_escape_string($con, $html_txt);
$sql = 'UPDATE table SET text = ' . $html_txt . ' WHERE id = ' . $id . '';
I die if I do not say:
Please use parameterized query
Please avoid using vulnerable sql statements.
use mysql_escape_string to support for html entities and may the text be the kwyword so use like this text
$id = 1;
$html =mysql_real_escape_string($html_txt);
$sql = 'UPDATE table SET `text` = '.$html.' WHERE id = '.$id.'';
This should be a comment - but it's a bit verbose.
It should be obvious to most PHP developers that the problem is lack of escaping of the HTML string, however that in itself is not a reason for this being a poor question.
You've not provided details of any attempt to investigate the problem yourself. "Doesn't work" is not a good description of what happenned - in this case the expected outcome is fairly obvious to me, but that's not always the case. I aslo know what the actual outcome would be - but you've not documented that either. In most occassions where code does not behave as expected, an error message will be reported somewhere - you should be looking for it. The DBMS would have returned a specific error message - which your code should poll - especially if you are running into problems.
If you had viewed the SQL you were sending (or included it in your post) this would also have helped diagnosis.
You should properly escape your HTML value. Though this solution is not optimal as it does not use parameterized queries (PDO, ....), try this:
$html = 'An günstigen Tagen "Paradies" ist es dienlich. Test/Test<br /><br />"Test"';
$id = 1;
$sql = 'UPDATE table SET text = '.mysql_real_escape_string($html).' WHERE id = '.$id.'';
i would suggest you use mySQli prepared statement, WHY : i think somewhere along the line your variable have funny characters that r messing up with your query..with prepared statements the query is send alone then after your variables are binded to it, pls check above code
$conn = new mysqli("localhost", "your username", "your pass", "your db");
$myString = "Your string here";
$id = 1;
$insertDB = $conn->prepare("UPDATE table SET text = ? WHERE id = ?");
$insertDB->bind_param('si', $myString, $id); //bind data, type string and int 'si'
$insertDB->execute(); //execute your query
$conn->close(); //close connection

Does this work to stop sql injections

I have been using the block of code below to supposedly stop sql injections. It is something someone showed me when I first started php(which was not that long ago)
I place it in every page just as shown on the open. I am wondering if it is effective? I do not know how to test for sql injections
<?php
//Start the session
session_start();
//=======================open connection
include ('lib/dbconfig.php');
//===============This stops SQL Injection in POST vars
foreach ($_POST as $key => $value) {
$_POST[$key] = mysql_real_escape_string($value);
}
foreach ($_GET as $key => $value) {
$_GET[$key] = mysql_real_escape_string($value);
}
My typical insert and update queries look like this
$insert = ("'$email','$pw','$company', '$co_description', '$categroy', '$url', '$street', '$suite', '$city', '$state', '$zip', '$phone', '$date', '$actkey'");
mysql_query("INSERT INTO provider (email, pw, company, co_description, category, url, street, suite, city, state, zip, phone, regdate, actkey) VALUES ($insert)") or die ('error ' . mysql_error());
mysql_query("UPDATE coupon SET head='$_POST[head]', fineprint='$_POST[fineprint]', exdate='$exdate', creationdate=NOW() WHERE id='$cid'") or die ('error ' . mysql_error());
That's somewhat effective, but it's suboptimal -- not all of the data you receive in _GET and _POST will go into the database. Sometimes you might want to display it on the page instead, in which case mysql_real_escape_string can only hurt (instead, you'd want htmlentities).
My rule of thumb is to only escape something immediately before putting it into the context in which it needs to be escaped.
In this context, you'd be better of just using parameterized queries -- then escaping is done for you automatically.
This is not enough.
1. You're missing cookies, $_COOKIE variable.
2. If you use $_REQUEST you're in trouble.
3. You didn't show your queries, you must enquote each variable with single quotes '' when you put it into query (especiall when the data is supposted to be an integer and you might think that quote is not necessary in that case, but that would be a big mistake).
4. Data used in your query could come from other source.
The best way is to use data binding and have the data escaped automatically by the driver, this is available in PDO extension.
Example code:
$PDO = new PDO('mysql:dbname=testdb;host=127.0.0.1' $user, $password);
$stmt = $PDO->prepare("SELECT * FROM test WHERE id=? AND cat=?");
$stmt->execute(array($_GET["id"], $_GET["cat"]));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
You can also bind data using string keys:
$stmt = $PDO->prepare("SELECT * FROM test WHERE id = :id AND cat = :cat");
$stmt->execute(array(":id" => $_GET["id"], ":cat" => $_GET["cat"]));
If you want to learn PDO, you might find useful these helper functions I use:
http://www.gosu.pl/var/PDO.txt
PDO_Connect(dsn, user, passwd) - connects and sets error handling.
PDO_Execute(query [, params]) - only execute query, do not fetch any data.
PDO_InsertId() - last insert id.
PDO_FetchOne(query [, params]) - fetch 1 value, $count = PDO_FetchOne("SELECT COUNT(*) ..");
PDO_FetchRow(query [, params]) - fetch 1 row.
PDO_FetchAll(query [, params]) - fetch all rows.
PDO_FetchAssoc(query [, params]) - returns an associative array, when you need 1 or 2 cols
1) $names = PDO_FetchAssoc("SELECT name FROM table");
the returned array is: array(name, name, ...)
2) $assoc = PDO_FetchAssoc("SELECT id, name FROM table")
the returned array is: array(id=> name, id=>name, ...)
3) $assoc = PDO_FetchAssoc("SELECT id, name, other FROM table");
the returned array is: array(id=> array(id=>'',name=>'',other=>''), id=>array(..), ..)
Each of functions that fetch data accept as 2nd argument parameters array (which is optional), used for automatic data binding against sql injections. Use of it has been presented earlier in this post.
Kind of.
The mysql_real_escape_string function takes the given variable and escapes it for SQL queries. So you can safely append the string into a query like
$safe = mysql_real_escape_string($unsafe_string);
$query = 'SELECT * FROM MyTable WHERE Name LIKE "' . $safe . '" LIMIT 1';
It does NOT protect you against someone putting malicious code into that query to be displayed later (i.e. XSS or similar attack). So if someone sets a variable to be
// $unsafe_string = '<script src="http://dangerous.org/script.js"></script>'
$safe = mysql_real_escape_string($unsafe_string);
$query = 'UPDATE MyTable SET Name = "' . $safe . '"';
That query will execute as you expect, but now on any page where you print this guy's name, his script will execute.
This is completely WRONG approach.
In fact, you are mimicking infamous magic quotes, which is acknowledged as a bad practice. With all it's faults and dangers.
To help you understand why your initial way was wrong Magic quotes in PHP
To help you understand why escaping has nothing to do with "data safety" yet not sufficient to protect your query: Replacing mysql_* functions with PDO and prepared statements
To help you understand when prepared statements not sufficient either and what to do in these cases: In PHP when submitting strings to the database should I take care of illegal characters using htmlspecialchars() or use a regular expression?
this is not to prevent SQL Injection the real escape method only add \ to the dangerous
characters like " or ' so a string with "hi"do'like" will become "hi\"do\'like\" so it is
less dangerous
this method is not always usefull ; in case you want to display the content of tha escaped
variable in a page it will only destroy it and make it less readable

Categories