Why am I not able to echo those things like adm_no, adm_dt, etc.?
require_once("lib/connection.php");
$adm_no = $_POST['adm_no'];
if (!$adm_no == "intval") echo "You Entered wrong Admission no Recheack Admission no";
exit();
$clas = $_POST['clas'];
$query = "SELECT * FROM $clas WHERE adm_no = $adm_no";
$result = mysql_query($query);
//searchs the query in db.
while ($result1 = mysql_fetch_array($result)) {
$adm_no = $result1['adm_no'];
$adm_dt = $result1['adm_dt'];
$name = $result1['name'];
$dob = $result1['dob'];
$f_name = $result1['f_name'];
$f_office = $result1['f_office'];
$f_o_no = $result1['f_o_no'];
$m_name = $result1['m_name'];
$m_office = $result1['m_office'];
$addr = $result1['addr'];
};
echo "Admission no = ";
$adm_no;
echo " <p>Admission Date </p>";
echo " <p>Name </p>";
echo " <p>Class </p>";
echo " <p>D.O.B </p>";
echo " <p>Father s name </p>";
echo " <p>Office address </p>";
echo " <p>Office No </p>";
echo " <p>Mother s name </p>";
echo " <p>Office Address </p>";
echo " <p>Address </p>";
echo " <p>Phone no </p>";
You have a syntax error
echo "Admission no = " ;$adm_no ;
Should be
echo "Admission no = " ;
echo $adm_no ;
or
echo "Admission no = " . $adm_no ;
Well, the following does print a string and then does nothing with the variable:
echo "Admission no = " ;$adm_no ;
You where probably going for:
echo "Admission no = " . $adm_no;
Apart from that, are you aware that the print logic is only evaluated once after the while loop has iterated all the results (if more than one). That is, the variables will hold the values of the last record only.
Here is the problem your exit(); is executing every time even if the input $adm_no is okay.
Change this
if (!$adm_no=="intval")
echo "You Entered wrong Admission no Recheack Admission no" ;
exit();
to
if (!$adm_no=="intval")
{
echo "You Entered wrong Admission no Recheack Admission no" ;
exit();
}
As I told you in the previous (deleted) question, you have an SQL-injection hole.
Here's how to fix it.
Change this code:
Coding horror
$adm_no = $_POST['adm_no'];
if (!$adm_no == "intval")
echo "You Entered wrong Admission no Recheack Admission no";
exit();
$clas = $_POST['clas'];
$query = "SELECT * FROM $clas WHERE adm_no = $adm_no";
Into this code, which is not exposed to SQL-injection dangers
$adm_no = mysql_real_escape_string($_POST['adm_no']);
if (!$adm_no == "intval") {
echo "You Entered wrong Admission no Recheack Admission no"; exit();
}
$allowed_tables = array('table1', 'table2');
$clas = $_POST['clas'];
if (in_array($clas, $allowed_tables))
{
$query = "SELECT * FROM `$clas` WHERE adm_no = '$adm_no'";
}
I know that the If will only accept integers, but the if in your previous question was commented out, therefor it comes and goes, so always escape your inputs before injecting them into your query!
Note how the if in your code does not work because you forgot to enclose the body after the then in brackets {}, causing the exit(); to always be executed.
For more info on SQL-injection see: How does the SQL injection from the "Bobby Tables" XKCD comic work?
And for info on why mysql-real-escape_string or PDO doesn't work with dynamic table names
see: How to prevent SQL injection with dynamic tablenames?
And: Sample code to fix this particular SQL-injection hole
XSS hole
To fix a possible XSS hole, don't do
Coding horror
echo "Admission no = ".$adm_no;
But do this instead:
echo "Admission no = ".htmlspecialchars($adm_no);
In your case it seems that $adm_no can only hold an integer, but I don't have the table definition so I cannot be sure of that. It's best to be on the safe side and always escape dynamic output using htmlspecialchars.
See: What are the best practices for avoiding xss attacks in a PHP site
Statement 1: echo "Admission no = " ;
Statement 2: $adm_no ;
You aren't echoing the variables.
You should probably have something like:
<p>Admission no = <?php echo htmlspecialchars($adm_no); ?></p>
The way you assign the variables in the loop doesn't make any sense: if your SQL query returns more than 1 row, your code will simply replace the values. You probably want to echo the results inside the loop.
There is a syntax error here: echo "Admission no = " ;$adm_no ;.. it should be echo "Admission no = ".$adm_no;
When you are echoing the results, you are not actually echoing the variables: echo " <p>Admission Date: $adm_dt </p>";
Because echo accepts parameters as comma-separated list, like
echo $one, "two"
Using comma is also possible, but better just use heredoc syntax which support variable substitution, if you need to output large chunk of text with newlines
echo <<<HEREDOC
Your text with $variables or {$variables} here
with newlines and other nifty plaintext formatting
HEREDOC;
Related
I would like to do something quite simple but I dont know the right code in php.
I have a variable $go which content is GO:xxxxx
I would like to query that if the content of a variable has the pattern "GO:" and something else, echo something, but if not, echo another thing
I want to declare an if statement like:
if (preg_match('/GO/', $go) {
echo "something";
}
else {
echo "another thing";
But I cannot make it work...
I want to embed this statement between this portion of my script:
$result = mysqli_query($enlace,"select count(distinct name2) as total from " . $table . " where go_id like '%" . $go . "%'");
$items = mysqli_fetch_assoc($result);
echo "<br/>";
echo "<b> The total number of genes according to GO code is:</b> " . $items['total'];
mysqli_free_result($result);
$result2 = mysqli_query($enlace,"select count(distinct name2) as total from " . $table . " where db_object_name like '%" . $go . "%'");
$items2 = mysqli_fetch_assoc($result2);
echo "<br/>";
echo "<b>The total number of genes according to GO association is:</b> " . $items2['total'];
mysqli_free_result($result2);
As it is right now, the variable $go can have a value like GO:xxxx or a random sentence, and, with this code, I get two strings, one with value 0 and another with value according to the total apperances matching $go content.
What I want is to declare an if statement so that it just prints one string, the one that has the number of matches according to $go content, but not both.
Any help?
Use strpos():
if (strpos($go, 'GO:') !== false) {
echo 'true';
}
Try this
echo (!strpos($go, 'GO:')) ? "another thing" : "something";
Will surely work
This question already exists:
PHP's white screen of death [duplicate]
Closed 6 years ago.
I am currently in a class at school and we have to link our MySQL database with our website using php. I already made and populated my tables in MySQL. My professor sent us this chunk of code to display the table info on our websites. However when I run it nothing happens and I haven't learned enough about php to know why it is not working. I used my correct host name, password, ect. But it won't work and when he does the tutorial online in the video it works for him.
This is the code I am using.
<html>
<head>
<title>Query All Movies from Database</title>
<body>
<?
# $db = mysql_pconnect("localhost","username","password");
if (!$db)
{
echo "ERROR: Could not connect to database. Please try again later.";
exit;
}
mysql_select_db("database name");
$query = "select * from movie";
$result = mysql_query($query);
$num_results = mysql_num_rows($result);
echo "<p>Number of movies found: ".$num_results."</p>";
for ($i=0; $i < $num_results; $i++)
{
$row = mysql_fetch_array($result);
echo "<p>";
echo htmlspecialchars( stripslashes($row["movieid"]));
echo "<br>";
echo htmlspecialchars( stripslashes($row["title"]));
echo "<br>";
//echo htmlspecialchars( stripslashes($row["directorid"]));
//echo "<br>";
echo htmlspecialchars( stripslashes($row["year"]));
echo "<br>";
echo htmlspecialchars( stripslashes($row["genre"]));
echo "<br>";
echo htmlspecialchars( stripslashes($row["runtime"]));
echo "<br>";
echo htmlspecialchars( stripslashes($row["plotdescription"]));
echo "<br>";
echo htmlspecialchars( stripslashes($row["comments"]));
echo "<br>";
echo "</p>";
}
?>
</body>
</html>
This is the output I am getting.
Directly to the screen.
Number of movies found: ".$num_results."
"; for ($i=0; $i < $num_results; $i++) { $row = mysql_fetch_array($result); echo "
"; echo htmlspecialchars( stripslashes($row["movieid"])); echo "
"; echo htmlspecialchars( stripslashes($row["title"])); echo "
"; //echo htmlspecialchars( stripslashes($row["directorid"])); //echo "
"; echo htmlspecialchars( stripslashes($row["year"])); echo "
"; echo htmlspecialchars( stripslashes($row["genre"])); echo "
"; echo htmlspecialchars( stripslashes($row["runtime"])); echo "
"; echo htmlspecialchars( stripslashes($row["plotdescription"])); echo "
"; echo htmlspecialchars( stripslashes($row["comments"])); echo "
"; echo "
"; } ?>
I did alot of research and read the links and here is the working code! Thanks for helping teach me!! This site is so great! You guys are awesome!
<?php
$servername = "localhost";
$username = "ursername";
$password = "password";
$dbname = "database name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT movieid, title, directorid, year, genre, runtime, plotdescription, comments FROM movie";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Movie ID: " . $row["movieid"]. "<br>Title: " . $row["title"]. "<br>Director ID: " . $row["directorid"]. "<br>Year: " . $row["year"]. "<br>Genre: " . $row["genre"]. "<br>Run Time: " . $row["runtime"]. "<br>Plot Description: " . $row["plotdescription"]. "<br>Comments: " . $row["comments"]." <br><br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Don't use that code - that snippet is not secure these days. You should be using one of the newer connection methods like PDO or MySQLI. I prefer the latter, try using the docs on PHP's site to set up your stuff.
http://php.net/manual/en/function.mysqli-connect.php
The only reason I could imagine that your teacher is using this method is either they don't know any better or they are using a very old version of PHP.
Older MySQL functions are procedural and get wonky when writing in OOP (object oriented programming) because they are manually escaped. The newer mysqli_ functions work with both procedural and OOP and support prepared statements. Prepared statements are safer because they parameterize the values so you run into less issues with SQL injection and other vulnerabilities. You also get some speed enhancements because the prepared statements only have to parsed on the preparation and not the execution. So if you use a lot of the same parameters you get some extra speed!
PDO also supports prepared statements, but its a little more complex for newcomers because it introduces an abstraction layer (basically you build the query in PHP instead of raw SQL statements). This was a turn off for me when I first started so I would try getting good at the MySQLi stuff before you look too deep into PDO.
There are so many fundamental issues here, but it seems like the issue with your output being wrong is because you're concenating the echo string, and doing wrong. With PHP you can put variables inside of double quotes and it will still parse correctly. And as I said, the code you have posted cannot be outputting that.
So change your first echo line to this and see what happens.
echo "<p>Number of movies found: $num_results</p>";
I always say, it's far better to teach yourself something than learn from a so called professor. He has given you depreciated code, that is now removed in PHP 7. He has told you i don't know what's wrong with your code and completely steered you in the wrong direction for secure, modern web development. This professor has no business teaching anyone PHP.
I am looking to be able to search a SQL database using a form and output the finds on the screen.
This is my code:
$query = "SELECT * FROM documents WHERE DocumentName = '%".$DocumentName."%'AND county = '".$county."' OR acreage = '".$acreage."' AND grantor = '".$grantor."' OR grantee = '".$grantee."' ORDER by 'DocumentName'" ;
$result=$db->query($query);
$num_results=$result->num_rows;
echo "<p>Number of documents found: ".$num_results."</p>";
for($i=0; $i <$num_results; $i++){
$row=$result->fetch_assoc();
echo"<p>".($i+1).".County: ";
echo htmlspecialchars(stripslashes($row['county']));
echo "<br />Acreage: ";
echo stripslashes($row['acreage']);
echo "<br />Grantor: ";
echo stripslashes($row['grantor']);
echo "<br />grantee: ";
echo stripslashes($row['grantee']);
echo "<br />Lessor: ";
echo stripslashes($row['DocumentName']);
echo "<br />PDF: ";
echo stripslashes ("" .$row['PDF'] . "<br>");
echo "</p>";
}
$result->free();
$db->close();
It selects and outputs the information. The thing is I need people to be able to leave a field blank the search form however this causes all data to be displayed. If they type in the county and leave everything else blank I want it to pull only that county records.
You can break where clause conditions like:
$where = '';
$where .= empty(county) ? '' : "AND county='$county' ";
...
And inject $where in the query.
Try something like this (to display that data only if associated form field is send and not empty)
if(isset($_POST['country']) && strlen($_POST['country'])>0) echo ($i+1).".County: ". htmlspecialchars(stripslashes($row['county']));
if(isset($_POST['acreage']) && strlen($_POST['acreage'])>0) echo "<br />Acreage: ". stripslashes($row['acreage']);
// ...
I would recommend checking the post values are set and storing where conditions in an array and then using implode to make a string for use in your query.
if(isset($_POST['country']) && strlen($_POST['country'])) {
$where[] = "country = '$country'";
}
if(isset($_POST['acreage']) && strlen($_POST['country'])) {
$where[] = "acreage = '$acreage'";
}
....
$where = isset($where) ? ' WHERE '.implode(' AND ',$where) : '';
$query = 'SELECT * FROM documents'.$where;
It is also worth noting that you have no protection from SQL injection attacks, you need to sanitise your input.
I have a table with about 500,000 rows, and need to query it to retrieve results. Basically the user just inputs a case number, and then I want to execute the following query and display the results using a while loop
if (!empty($_POST["casenum"])) {
$result2 = mysql_query("SELECT Box_Content.case_number, Transfer.number, Transfer.location, Box.number FROM Box_Content, Transfer, Box WHERE Box_Content.box_id = Box.id and Box.transfer_id = Transfer.id and Box_Content.case_number = '".$_POST['casenum']."'");
while ($row = mysql_fetch_array($result2)) {
echo "Case number: ".$casenum." text ";
echo "<br />";
}
} else {
echo "<h4>WARNING!!! Search criteria entered not valid. Please search again.</h4>";
}
What am I doing wrong here?
EDIT:
It works now if only one row is returned, but for two rows, it seems to be trying to print the entire table...
$casenum = $_POST["casenum"];
echo "<br />The case number entered is: $casenum<br />";
if (!empty($_POST["casenum"]))
{
$result2 = mysql_query("SELECT Box_Content.case_number, Transfer.number as transfer_number, Transfer.location as transfer_location, Box.number as box_number FROM Box_Content, Transfer, Box WHERE Box_Content.box_id = Box.id and Box.transfer_id = Transfer.id and Box_Content.case_number = '" . $_POST['casenum'] . "'");
while($row = mysql_fetch_array($result2))
{
print_r ($row);
echo "<br />";
echo "<b>Case number: </b>" . $row['case_number'] ."<br />";
echo "<b>Transfer number: </b>" . $row['transfer_number'] ."<br />";
echo "<b>Transfer location: </b>" . $row['transfer_location'] ."<br />";
echo "<b>Box number: </b>" .$row['box_number'] ."<br />";
}
}
else
{
echo "<h4>WARNING!!! Search criteria entered not valid. Please search again.</h4>";
}
var_dump($_POST);
Try:
while ($row = mysql_fetch_array($result2)) {
echo "Case number: ". $row['Box_Content.case_number'] ." text ";
echo "<br />";
}
$row['case_number'] will output the case_number retrieved for each row in your resultset.
However, you should look into doing one of two things:
Start using best practices.
Start using a non-deprecated SQL library (mysqli, PDO).
This query is susceptible to SQL injection:
"SELECT Box_Content.case_number, Transfer.number, Transfer.location, Box.number
FROM Box_Content, Transfer, Box
WHERE Box_Content.box_id = Box.id and Box.transfer_id = Transfer.id
and Box_Content.case_number = '".$_POST['casenum']."'"
Use mysql_real_escape_string($_POST['casenum']) to patch this.
Reference: http://php.net/manual/en/function.mysql-real-escape-string.php
The mysql_* functions have long been deprecated due to unprepared statement operations. Look into either mysqli or PDO for your project instead.
What am I doing wrong here?
1) $casenum isn't set in your code... (Please tell me it is nothing and you don't have register superglobals turned on?!) You would probably want $row['case_number']
2) But anyway, that's not really what you are doing wrong... Your biggest mistake is using user input without any kind of validation or sanitization...
Imagine if $_POST["casenum"] was equal to...
' or 1=2 union select user,password,email,salt from users
You seem to be using $casenum from nowhere.
Try:
while($row = mysql_fetch_assoc($result2))
echo "Case number: ".$row['number']." text <br />";
When using the mysql_fetch functions assoc will bring back named indexed data, num will bring back numberic indexed data and array will bring back both, so try to use one or the other.
Then when you do $row = mysql_fetch_assoc($result2) your essentially saying for each row of data returned store it as a (in this case associative) array in $row, so you can then access your data via the standard array commands ($row['foo']).
I am revisiting php and mySQL from a long time off.
mysql_select_db($database_conn, $conn);
$query = sprintf("SELECT DISTINCT Username FROM Entries ");
$result = mysql_query($query);
$row_results = mysql_fetch_assoc($result);
<?php do {
//$name = $row_results['Username'];
//echo $name, "<br/>";
echo '<a href=\"$row_results['Username'],.php\">';
echo '$row_results['Username'],'s overview </a><br/>';
}
while ($row_results = mysql_fetch_assoc($result)); ?>
What I am trying to do is echo out the link from the results the link is in the form username.php the username is stored in the database.
I have used single quotes and double quotes with escaped /" in but get different errors I know its going to be something as simple as a ; or " .
If you could be as kind to explane what is wrong abd if there is a better way to do this?
The query is correct and the commented out code also works on its own.
Thanks
You cannot parse variables through single quotes:
echo '<a href=\"$row_results['Username'],.php\">';
use
echo '<a href="'.$row_results['Username'].'">';
mysql_select_db($database_conn, $conn);
$query = sprintf("SELECT DISTINCT Username FROM Entries ");
$result = mysql_query($query);
$row_results = mysql_fetch_assoc($result);
<?php do {
//$name = $row_results['Username'];
//echo $name, "<br/>";
echo '<a href="'.$row_results['Username'].'php">';
echo $row_results['Username'].'\'s overview </a><br/>';
}
while ($row_results = mysql_fetch_assoc($result)); ?>
Looks to me like the concatenation of your html string and the username is incorrect.
Currently, your string that you are writing to the page is
<a href=\"$row_results['Username'],.php\">
What you need to be doing is joining the html with the value coming out from the database.
This can be done like so:
echo '<a href=\"'.$row_results['Username'].'.php\">';
echo $row_results['Username'].'\'s overview </a><br/>';
Notice the '.' to concatenate two potions of the string, and the escapement of the apostrophe in the 's
Here are your errors :
Even though you are using DISTINCT in your SQL Query, there might be multiple entries, so you must use a while loop.
You had a comma in there (probably by typo).
You need to escaping the php variable.
So after doing the above, this is what it should be.
while ($row_results = mysql_fetch_assoc($result)) {
echo '<a href="' .$row_results["Username"]. '.php">';
}
try:
echo '<a href="'.$row_results['Username'].'.php">';
echo $row_results['Username'].'\'s overview </a><br/>';
Seems like you got pretty mixed up with the " and ' there. You should really avoid using anything other than ' - it will only bite you on the long run.
Also: You concatenate with ., not with ,.
mysql_select_db($database_conn, $conn);
$query = sprintf('SELECT DISTINCT Username FROM Entries ');
$result = mysql_query($query);
$row_results = mysql_fetch_assoc($result);
do {
$name = $row_results['Username'];
echo $name.'<br/>';
echo '<a href="'.$name.'.php">';
echo $name.'\'s overview </a><br/>';
} while ($row_results = mysql_fetch_assoc($result)); ?>