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
Related
I have the following code:
$indtag = '';
foreach($pretag as &$indtag) { //cycles through tags, puts quotes into check by tag
$quote = mysqli_query($mysqli, "SELECT `id`, `$indtag` FROM `beyonce` WHERE `$indtag` LIKE '%$indtag%'");
while($row = mysqli_fetch_assoc($quote)) {
echo $row['$indtag'];
echo $row['id'];
}
}
The table has fields for ids, quotes, then an individual column for each tag (ang for anger being an example). pretag is an array full of tags (rom is romance, ang is anger, dece is deception) that I'm running through, trying to find quotes with those IDs and tags. The statement works fine in SQL when I run it with ang, it selects the IDs fine, but when I try to select the column/field for a tag using a variable, nothing comes back. Any ideas?
You're using the variable $indtag where you should be using the column name indtag:
SELECT `id`, `$indtag` FROM `beyonce` WHERE `$indtag` LIKE '%$indtag%'
^ ^
And as #tadman points outs, don't do it this way, use mysqli_stmt_bind_param with a prepared statement or you are in for a wild ride.
This line in your code doesn't need quotes.
echo $row['$indtag']; // Won't work
echo $row[$indtag]; // Will work
I am attempting to create a function that will insert items (and will do the same to edit) items in a database through a form. I have the form and the PHP - and when I run the function, I get the correct database name to pull and the variable names to pull along with the values I input, but I then see a database error? Any help would be great (I'm still newer to PHP really and pulling out some hair)
Config File:
$hostname = 'localhost';
$username = 'DEFINED';
$password = 'DEFINED';
$database = 'DEFINED';
$table = 'recipes';
require('../config.php');
$link = mysql_connect($hostname,$username,$password);
mysql_select_db($database,$link);
/* Get values and submit */
$rid = mysql_real_escape_string($_POST['rid']);
$name = mysql_real_escape_string($_POST['name']);
$category = mysql_real_escape_string($_POST['category']);
$tags = mysql_real_escape_string($_POST['tags']);
$search_tags = mysql_real_escape_string($_POST['search_tags']);
$description = mysql_real_escape_string($_POST['description']);
$description2 = mysql_real_escape_string($_POST['description2']);
$recipeAbout = mysql_real_escape_string($_POST['recipeAbout']);
$ingredients_1 = mysql_real_escape_string($_POST['ingredients_1']);
$directions_1 = mysql_real_escape_string($_POST['directions_1']);
$query = "INSERT INTO $table (name, category, tags, search_tags, description,description2, recipeAbout, ingredients_1,directions_1) VALUES ('$name','$category','$description','$description2' $tags','$search_tags','$description','$recipeAbout','$ingredients_1','$directions_1')";
echo $query;
Besides the missing comma in '$description2' $tags' => '$description2', $tags' which you said had been added afterwards, and signaled by Ryan: there's also a missing quote, so change it to '$description2', '$tags' and having 2x '$description' variables, remove one.
VALUES
('$name','$category','$tags','$description','$description2', '$search_tags','$recipeAbout','$ingredients_1','$directions_1')";
However, the most important part to querying, is that you must use mysql_query() which you are not using => mysql_query() which is why data isn't being inserted, once you've fixed the syntax errors.
mysql_query() is the essential part.
Add the following to your code:
if(mysql_query($sql,$link)){
echo "Success";
}
else{
echo "Error" . mysql_error();
}
Plus, use prepared statements, or PDO with prepared statements.
You're using a deprecated library and open to SQL injection..
Plus make sure you have assigned $table to the table you wish to enter data into. It's not shown in your question.
You also did not show what your HTML form contains. Make sure that you are using a POST method and that all elements are named with no typos.
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);
Sidenote: Error reporting should only be done in staging, and never production.
EDIT: and using mysqli_
As a quick test, try the following and replacing the values in the line below with your own.
<?php
$link = mysqli_connect("host","username","password","database")
or die("Error " . mysqli_error($link));
$table = "recipes";
$name = mysqli_real_escape_string($link,$_POST['name']);
mysqli_query($link,"INSERT INTO `$table` (`name`) VALUES ('".$name."')")
or die(mysqli_error($link));
?>
If that still does not work, then you need to check your database, table, column name(s), including types and column lengths.
Lot's of stuff wrong here...
You're missing a quote on the second of these two items, as well as either a string concat or a comma: '$description2' $tags'
You've also got your order messed up for tags, search tags, and description 1/2.
$description is in there twice (you have 9 columns defined and 10 values in your statement)
You don't seem to have declared a value for $table
As Fred -ii- has pointed out in his answer, you're missing mysql_query() to actually run it. I assumed you have it further down in your code, but it's missing from the post, which is causing some confusion...
Also, consider updating to use mysqli instead of mysql functions.
what are you echoing $query for?
You do not have any reason to do that except if you just want to use it as a string variable.
it should be mysql_query($query);
What is the exact "database error" error you are getting?
I suggest reading this article about PDO
If you can't insert the data correctly, this might be your problem too.
I have a table with one column I want to populate, The PHP form has 4 fields
Field 1
Field 2
Field 3
Field 4
On submit of the form I want to enter the data from the 4 fields into on column into my database sepperated with a ^
So Basically the input data must look like this
Field1^Field2^Field3^Field4
Normally I insert into a Field
$sql = "insert into etrack_clients set
Field1 = '".$Field1."',
Field2= '".$Field2."'" ;
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
print_r($_POST);
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
}
How would I insert with the ^ and no spacing, On the above code this inserts into it's own Column's now into the same column
As I understood, you need to place the four fields value into one column separated by a ^. Here's a query that does this, try it:
$sql = "INSERT INTO etrack_clients SET field = '{$_POST['field1']}^{$_POST['field2']}^{$_POST['field3']}^{$_POST['field4']}'";
Please note that this above query is not safe and can cause serious problem if not escaped. In order to escape it, web developers used to use mysql_real_escape_string() in order to escape special characters. This method will be deprecated starting from PHP 5.5.0. Alternatively, you can use PDO prepared statements to run queries safely.
PDO prepared statements
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.
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