How do I load data to textbox from mysql - php

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.

Related

Read from sql stops when I include WHERE using php

I have a script where I would like to read from a table and list out all the "tasks" where the column check = 1. My script works fine and will list all the tasks....until I include the WHERE. Then nothing will be read into the page. What am I doing wrong?
The problem is the WHERE check="1"
$sql = mysql_query('SELECT tasks FROM tasks WHERE check="1"');
while($row = mysql_fetch_array($sql))
{
echo $row['tasks'];
echo "<br />";
}
The table name is "tasks" and the two columns are "tasks" (varchar255) and "check" (int11)
Immediate problem
Why is nothing displayed? Most likely you have an SQL error. But you don't print it anywhere.
Displaying mysql errors with PHP
//this is a bad query, this time it is intentional
$sql = mysql_query('SELECT tasks FROM tasks WHERE check="1"');
if($sql)
{
//do processing here, no error
while($row = mysql_fetch_array($sql))
{
echo $row['tasks'];
echo "<br />";
}
}
else
{
//output error, or handle it in any other way you like
echo mysql_error();
}
And your problem is most likely quotes -- UPDATE: on multiple levels:
Level 1
Double quotes " is not ok in SQL statement. Use single quote ' for string constants, and backtick ` for enclosing object names (tables, columns, etc.)
Swap quotes:
$sql = mysql_query("SELECT tasks FROM tasks WHERE check='1'");
Escape quotes:
$sql = mysql_query('SELECT tasks FROM tasks WHERE check=\'1\'');
Do you need quotes at all? this seems to be a numeric value...
Only numeric value, no type conversion whatsoever:
$sql = mysql_query('SELECT tasks FROM tasks WHERE check=1');
Level 2
The fact that the check keyword is reserved in MySQL doesn't help either. You can use it to identifz objects, but with precautions: properly enclosed in backticks (`):
$sql = mysql_query('SELECT tasks FROM tasks WHERE `check`=1');
Strongly consider
leave mysql_* behind once and for all. Deprecated! Not Safe! Here be dragons!
best would be to properly use PDO, through prepared statements
read up on SQL injection. That can be bad news any day.
best would be to properly use PDO, through prepared statements
Agreed, as ppeterka said, you don't need quotes at all:
$sql = mysql_query('SELECT tasks FROM tasks WHERE check=1');
Consider also that using quotes will prevent your query from following an eventual index on "check" column.
You really should be using mysqli
but you can try something like SELECT tasks FROM tasks WHERE check = 1,
$sql = mysql_query("SELECT tasks FROM tasks WHERE check='1'");
while($row = mysql_fetch_array($sql))
{
echo $row['tasks'];
echo "<br />";
}

Possible to use php tag inside query string?

I have multiple values passed through a POST form (from multiple check boxes of previous page) and I stored them into an array $vals. Now I want to write a query string (in a while loop) that generates a slightly different query depending on how far in the loop it has been.
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>
But it doesn't seem to work this way? I thought that by having double quotes for query, the
echo $vals[$i]
would generate the actual value of the current index in $vals[$i] and not the literal string? Is this what's happening? Can I not have php inside a query string that the mysql servers would accept?
lets just say i have a fooID in my server table that is '12345'. Even if I set $vals='12345' and write:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
it still doesn't work. I guess my general question would be: is it possible to write/get values of variables in a query string, and if not, is there another way around my situation? Any help is appreciated. Thanks!
You should not be placing the un-sanitized $_POSTed values into a SQL query. Look into using paramaterized arguments and mysqli.
You can output variables using the syntax:
$myVar = 'toast';
$combined = "I like $myVar";
However, this will not work as you would like for an array.
For an array, you'll want to look into using something like php's implode() to convert your array into a string first.
first of all never do queries in loop.
Second of all never use straight $_POST or $_GET or whatever client is passing in queries because you can be harmed by sql injections.wiki and also clearing data for mysql in php
ok so how it should be done (i am saying only about first one. second one i dont know how to make it without oop ).
<?php
$vals=($_POST['selectedIDs']);
$vals = implode(',',$vals);
$query = "SELECT * FROM List foo WHERE foo.fooID IN ($vals)";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
echo "YES IT WORKS!";
var_dump($row); //you will see all the data in one row
}
}?>
You have an extra echo in your SQL string:
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
It should be:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals[$i]";
Generally, it's a BAD idea to construct SQL strings from user input. Use prepared statements instead. Check here for more info on prepared statements:
http://php.net/manual/en/pdo.prepared-statements.php
Thanks you guys for the advice but it turned out, my code didn't execute correctly because of a syntax error (and the extra echo statement). my original code was missing quotation marks around $vals[$i]. This is a mysql syntax mistake because it didn't accept foo.fooID=12345 but did for foo.fooID='12345'. Here is the final code that solved it
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = '$vals[$i]'";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>

Difficulty passing GET variable?

Hi I am trying to display specific entries in a database by appending the variable name to a URL like:
echo '<td><a class="index_table" href="includes/view.php?id=$row[id]>$row[Orderno]">
and then in my view.php I have:
<?php
include 'connect.php';
//Display the Data//
$id=$_GET['id'];
$result=mysql_query("select * from Products where ID=$id");
$row=mysql_fetch_object($result);
echo "<table>";
echo "
<tr bgcolor='#f1f1f1'><td><b>ID</b></td><td>$row->ID</td></tr>
However the specific ID is not being passed to the script, and the table in view.php is blank. When changing the where clause to 'where id = '1' the correct product displays. So I know that this is working.
Many Thanks
Basic PHP syntax: Strings quoted with ' do not interpolate variable values:
echo '<td><a class="index_table" href="includes/view.php?id=' . $row['id'] . '>' . $row['Orderno'] . '">';
^^^^^^^^^^^^^^^^^^
note that you're wide open to SQL injection attacks and are just begging to get your server pwn3d.
First problem:
You have to put the array string indexes into a paranthesis:
echo '<td><a class="index_table" href="includes/view.php?id='.$row['id'].'">'.$row['Orderno'].'</a></td>';
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^
Second problem:
Your ID in the URL could easily be replaced with '; DELETE FROM table # thus allowing an attacker to perform a SQL injection! Always sanitize any user input (POST) or GET parameters that takes a part in SQL queries:
$id = mysql_real_escape_string($_GET['id']);
or for that case (when an integer is expected)
$id = (int) $_GET['id'];
Suggestion: do not use mysql_* functions but use PDO with (real!) prepared statements or at least mysqli_* functions with proper input sanitization.
Two big issues here. First, your link is not working correctly because you are using single-quotes in your echo, meaning the variables are not interpolated, so you must change to something like either of the following:
echo "<td><a class=\"index_table\" href=\"includes/view.php?id={$row['id']}>{$row['Orderno']}\">";
or
echo '<td><a class="index_table" href="includes/view.php?id=' . $row['id'] . '>' . $row['Orderno'] . '">';
WARNING - SECURITY BREACH
In your later code you are leaving yourself open to SQL Injection attack; some references to what this is can be found at OWASP and Wikipedia, and are very important to learn about. To protect yourself, you must escape data before sending it to a query. Here are some ways to do that:
$id = mysql_real_escape_string($_GET['id']);
$result=mysql_query("select * from Products where ID = '$id'");
or
$id = $_GET['id'];
if (!ctype_digit((string)$id)) {
die('Invalid ID: ' . htmlentities($id));
}
$result=mysql_query("select * from Products where ID = '$id'");
In the first example, I use mysql_real_escape_string to make the data safe for embedding in a query (note that I also added quotes around the variable); in the second, I did a data check to make sure it contained only digits (note that the length should also be checked, but this is a quick example), and if it contained something other than digits, we spit out an error message and don't run the query.
Change your query like, I added two ' between $id
$result=mysql_query("select * from Products where ID='$id'");
And see.
You're not actually including the value of the $id variable in the query. Take a look at this answer for options on how to do this:
How can I prevent SQL injection in PHP?
PDO
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array(':name' => $name));
foreach ($stmt as $row) {
// do something with $row
}
mysqli
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
You shouldn't put the GET variable directly into the query like that, you should do some sanity checks like checking it's numeric etc. to avoid sql injection.
No doubt you will have answers saying the mysql_ functions are deprecated aswell but I don't think that's relevant to the question.
In your link you have
<td><a class="index_table" href="includes/view.php?id=$row[id]>$row[Orderno]">
you don't have the right syntax for the array elements, try
<td><a class="index_table" href="includes/view.php?id=' . $row['id'] . '>' . $row['Orderno'] . '">
It looks like a malformed URL in the tag, plus PHP doesn't parse variables in single quoted strings. I think you just need this:
echo "<td><a class='index_table' href='includes/view.php?id=$row[id]'>$row[Orderno]</a></td>";
You don't need to change the code in view.php but I would recommend filtering the _GET variable this way:
$id = (int)$_GET['id'];
Try
echo "<td><a class='index_table' href='includes/view.php?id=".$row['id'].">".$row['Orderno']."'>";
and
<?php
include 'connect.php';
//Display the Data//
$id=$_GET['id'];
if(is_int($id))
{
$result=mysql_query("select * from Products where ID=$id");
$row=mysql_fetch_object($result);
echo "<table>";
echo "<tr bgcolor='#f1f1f1'><td><b>ID</b></td><td>$row->ID</td></tr>";
}
else
{
echo "<h1>Nice try silly... You aint hackin me!</h1>";
}
I also noticed in your original code you were missing some ending quotes and semi-colons. That may have been all that was wrong. But this should clear up your security issue and should work for your application
Good luck.

How to make an SQL query using variable column names?

I am making a query like this:
$b1 = $_REQUEST['code'].'A'; //letter 'A' is concatenated to $_REQUEST['code']
$a = $_REQUEST['num'];
echo $b1.$a;
$sql = "SELECT '".$b1."' FROM student_record1 WHERE id=".$a;
$result = mysql_query($sql);
if(!$result)
{
echo '<p id="signup">Something went wrong.</p>';
}
else
{
$str = $row[0]
echo $str;
}
Here $b1 and $a are getting values from another page. The 'echo' in the third line is giving a correct result. And I am not getting any error in SQL. Instead, I am not getting any result from the SQL query. I mean echo at the last line.
Don't do this, it breaks your relational model and is unsafe.
Instead of having a table with columns ID, columnA, columnB, columnC, columnD, columnE and having the user select A/B/C/D/E which then picks the column, have a table with three columns ID, TYPE, column and have TYPE be A/B/C/D/E. This also makes it easier to add F/G/H/I afterwards without modifying the table.
Secondly, with the extra column approach you don't have to build your SQL from input values like that. You can use prepared statements, and be safe from SQL Injection. Building SQL from unfiltered strings is wrong, and very dangerous. It will get your site hacked.
If you must use dynamic table/column/database names, you'll have to run them through a whitelist.
The following code will do:
$allowed_column = array('col1', 'col2');
$col = $_POST['col'];
if (in_array($col, $allowed_column)) {
$query = "SELECT `$col` FROM table1 ";
}
See: How to prevent SQL injection with dynamic tablenames?
For more details.

Search entire table? PHP MySQL

I have made the following search script but can only search one table column when querying the database:
$query = "select * from explore where site_name like '%".$searchterm."%'";
I would like to know how I can search the entire table(explore). Also, I would need to fix this line of code:
echo "$num_found. ".($row['site_name'])." <br />";
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Thanks for any help, here is the entire script if needed:
<?php
// Set variables from form.
$searchterm = $_POST['searchterm'];
trim ($searchterm);
// Check if search term was entered.
if (!$serachterm)
{
echo "Please enter a search term.";
}
// Add slashes to search term.
if (!get_magic_quotes_gpc())
{
$searchterm = addcslashes($searchterm);
}
// Connects to database.
# $dbconn = new mysqli('localhost', 'root', 'root', 'ajax_demo');
if (mysqli_connect_errno())
{
echo "Could not connect to database. Please try again later.";
exit;
}
// Query the database.
$query = "select * from explore where site_name like '%".$searchterm."%'";
$result = $dbconn->query($query);
// Number of rows found.
$num_results = $result->num_rows;
echo "Found: ".$num_results."</p>";
// Loops through results.
for ($i=0; $i <$num_results; $i++)
{
$num_found = $i + 1;
$row = $result->fetch_assoc();
echo "$num_found. ".($row['site_name'])." <br />";
}
// Escape database.
$result->free();
$dbconn->close();
?>
Contrary to other answers, I think you want to use "OR" in your query, not "AND":
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
Replace other_column with the name of a second column. You can keep repeating the part I added for each of your columns.
Note: this is assuming that your variable $searchterm has already been escaped for the database, for example with $mysqli->real_escape_string($searchterm);. Always ensure that is the case, or better yet use parameterised queries.
Similarly when outputting your variables like $row['site_name'] always make sure you escape them for HTML, for example using htmlspecialchars($row['site_name']).
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Make sure that both forms use the same method (post in your example). The <form> tag should have the attribute method="post".
Also, what is wrong with the line of code you mentioned? Is there an error? It should work as far as I can tell.
A UNION query will provide results in a more optimized fashion than simply using OR. Please note that utilizing LIKE in such a manner will not allow you to utilize any indexes you may have on your table. You can use the following to provide a more optimized query at the expense of losing a few possible results:
$query = "SELECT * FROM explore WHERE site_name LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE other_field LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE third_field LIKE '".$searchterm."%'";
This query is probably as fast as you're going to get without using FULLTEXT searching. The downside, however, is that you can only match strings beginning with the searchterm.
To search other columns of table you need to add conditions to your sql
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
But if you don't know that I would strongly advise going through some sql tutorial...
Also I didn't see anything wrong with this line
echo "$num_found. ".($row['site_name'])." <br />";
What error message are you getting?
Just add 'AND column = "condition"' to the WHERE clause of your query.
Be careful with adding lots of LIKE % conditions as these can be very slow especially if using a front wild card. This causes the RDBMS to search every row. You can optimize if you use an index on the column and only a trailing wildcard.
You are searching the whole table, just limiting the results to those where the site_name like '%".$searchterm."%'. If you want to search everything from that table, you need to remove the WHERE clause
Here's the corrected line. You had a few too many quotes in it.
echo $num_found.".".($row['site_name'])." <br />";
Regarding displaying the message, you have a typo in your code:
// Check if search term was entered.
if (!$serachterm)
should be:
// Check if search term was entered.
if (!$searchterm)
In the code you have written, !$serachterm always evaluates to true because you never declared a variable $seracherm (note the typo).
your code is very bugy for sql injection first do
do this
$searchterm = htmlspecialchars($searchterm);
trim($searchterm);
next
$query = mysql_real_escape_string($query);
finaly your search looks like this
$query = "select * from explore where site_name like '%$searchterm%';

Categories