Display mysql database query result on second pages - php

I have a mysql database with some data.here i display data on one page Now I want to display this data on next page please give me suggestion how I can do this .........
I need some modifications in this code like
I want to display table this table on next page(book.php page that is populated with the database)......
Second thing that I need to know is it possible to store the value of calendar in session variable (is it ???than how?)
<?php
if(isset($_POST['search'])){
$from = $_POST['from'];
$to = $_POST['to'];
$query = mysql_query("select * from schedule where Destinatio='$from' AND Arriva ='$to'");
$c = mysql_num_rows($query);
if (!$query) {
die('Invalid query: ' . mysql_error());
}
if($c>0)
{
?>
<table>
<tr align="center"><td width="120"><span class="style23">Destination</span> </td>
<td width="57"><span class="style23">Arrival</span></td>
<td width="121"><span class="style23">Departure time</span></td>
<td width="98"><span class="style23">Arrival Time</span></td>
<td width="44"><span class="style23">Fare</span></td>
<td width="85"><span class="style23">Bus_type</span></td>
<td width="84"><span class="style23">Total_Seats</span></td>
<td width="81"><span class="style23">Available</span></td>
<td width="52"> </td>
</tr>
</section>
<?php
while($r1 = mysql_fetch_array($query))
{
$schedule= $r1['id'];
$Destinatio = $r1['Destinatio'];
$Arriva= $r1['Arriva'];
$Departure_time = $r1['Departure_time'];
$Arrival_time = $r1['Arrival_time'];
$Fare = $r1['Fare'];
$Bus_type = $r1['Bus_type'];
$Total_Seats = $r1['Total_Seats'];
$bust = $schedule.'schedule';
$query1 = mysql_query("SELECT * from $bust where status='Available'");
echo $query1;
if (!$query1) {
die('Invalid query: ' . mysql_error());
}
$c = mysql_num_rows($query1);
?>
<tr align="center"><td><?php echo $Destinatio;?></td><td><?php echo $Arriva;?></td><td><?php echo $Departure_time;?></td><td><?php echo $Arrival_time;?></td><td><?php echo $Fare;?></td><td nowrap="nowrap"><?php echo $Bus_type;?></td><td><?php echo $c;?></td><td>Book
</td>
</tr></table>
</form>

There are three main ways to pass variables:
Using a form button using $_POST variables to pass the content
(generally best when you also have user input).
Using an HTML anchor link to pass the variables through $_GET
Using a SESSION variable that can be accessed on all pages on your site.
Using SESSION variables is the more secure way, but it the data isn't secret use the $_GET method.
To store something in a SESSION variable you need to use:
start_session();
$_SESSION['varname'] = value;
on the following page, you can read your SESSION variable just by using it's name. For example:
start_session();
echo $_SESSION['varname'];

Related

How to connect an HTML interface (to submit SQL statements) to a PHP file and then connect the PHP to my database?

I'm not sure how to connect my HTML interface to a PHP file to then connect to my database. I want to be able to enter SQL statements into my interface and have it retrieve and display data from my database?
Connect from client HTML to server with a PHP handler for GET or POST. In this handler method, implement your logic for database interaction for SQL statements.
MySQL is the most popular database system used with PHP.
I will try to explain this to you by storing data into the DB and getting the data from the DB to view in a table in the front end.Very often you will need to use a MySQL table to store data inside it and then output that data by using a PHP script. To display the table data it is best to use HTML, which upon filling in some data on the page invokes a PHP script which will update the MySQL table.
To populate a new database table with data you will first need an HTML page which will collect that data from the user. The following HTML code that and passes the information to a PHP script:
<form action="insert.php" method="post">
Value1: <input type="text" name = "field1" /><br/>
Value2: <input type="text" name = "field2" /><br/>
Value3: <input type="text" name = "field3" /><br/>
Value4: <input type="text" name = "field4" /><br/>
Value5: <input type="text" name = "field5" /><br/>
<input type="submit" />
</form>
The above HTML code will show the user 5 text fields, in which the user can input data and a Submit button. Upon clicking the Submit button the data submitted by the user will be passed to a script named insert.php.
That script can have a syntax similar to the following:
<?php
$username = "your_username";
$password = "your_pass";
$database = "your_db";
$mysqli = new mysqli("localhost", $username, $password, $database);
// Don't forget to properly escape your values before you send them to DB
// to prevent SQL injection attacks.
$field1 = $mysqli->real_escape_string($_POST['field1']);
$field2 = $mysqli->real_escape_string($_POST['field2']);
$field3 = $mysqli->real_escape_string($_POST['field3']);
$field4 = $mysqli->real_escape_string($_POST['field4']);
$field5 = $mysqli->real_escape_string($_POST['field5']);
$query = "INSERT INTO table_name (col1, col2, col3, col4, col5)
VALUES ('{$field1}','{$field2}','{$field3}','{$field4}','{$field5}')";
$mysqli->query($query);
$mysqli->close();
After the user submits the information, the insert.php script will save it in the database table. Then you may want to output that information, so that the user can see it on the page. The first command you will need to use is the SELECT FROM MySQL statement that has the following syntax:
SELECT * FROM table_name;
This is a basic MySQL query which will tell the script to select all the records from the table_name table. After the query is executed, usually you would want the result from it stored inside a variable. This can be done with the following PHP code:
<?php
$query = $mysqli->query("SELECT * FROM table_name");
The whole content of the table is now included in a PHP array with the name $result. Before you can output this data you should change each piece into a separate variable. There are two stages.
Now, we have to set up the loop. It will take each row of the result and print the data stored there. This way we will display all the records in the table:
$query = "SELECT * FROM table_name";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$field1name = $row["col1"];
$field2name = $row["col2"];
$field3name = $row["col3"];
$field4name = $row["col4"];
$field5name = $row["col5"];
}
/* free result set */
$result->free();
}
You can now write a full script to output the data. In this script the data is not formatted when it is printed:
<?php
$username = "username";
$password = "password";
$database = "your_database";
$mysqli = new mysqli("localhost", $username, $password, $database);
$query = "SELECT * FROM table_name";
echo "<b> <center>Database Output</center> </b> <br> <br>";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["col1"];
$field2name = $row["col2"];
$field3name = $row["col3"];
$field4name = $row["col4"];
$field5name = $row["col5"];
echo '<b>'.$field1name.$field2name.'</b><br />';
echo $field5name.'<br />';
echo $field5name.'<br />';
echo $field5name;
}
/*freeresultset*/
$result->free();
}
This outputs a list of all the values stored in the database. This will give you a very basic output which is not useful for a live website. Instead, it would be better if you could format it into a table and display the information in it. To apply formatting you need to use HTML to print the result by including the variables in the correct spaces. The easiest way to do this is by closing the PHP tag and entering HTML normally. When you reach a variable position, include it as follows:
<?php echo $variablename; ?>
in the correct position in your code.
You can also use the PHP loop to repeat the appropriate code and include it as part of a larger table.
The final output will be:
<html>
<body>
<?php
$username = "username";
$password = "password";
$database = "your_database";
$mysqli = new mysqli("localhost", $username, $password, $database);
$query = "SELECT * FROM table_name";
echo '<table border="0" cellspacing="2" cellpadding="2">
<tr>
<td> <font face="Arial">Value1</font> </td>
<td> <font face="Arial">Value2</font> </td>
<td> <font face="Arial">Value3</font> </td>
<td> <font face="Arial">Value4</font> </td>
<td> <font face="Arial">Value5</font> </td>
</tr>';
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["col1"];
$field2name = $row["col2"];
$field3name = $row["col3"];
$field4name = $row["col4"];
$field5name = $row["col5"];
echo '<tr>
<td>'.$field1name.'</td>
<td>'.$field2name.'</td>
<td>'.$field3name.'</td>
<td>'.$field4name.'</td>
<td>'.$field5name.'</td>
</tr>';
}
$result->free();
}
?>
</body>
</html>
This code will print out table content and add an extra row for each record in the database, formatting the data as it is printed.
I hope this will help you to solve your issue.

PHP + MySQL + Cookies, why is this not loading properly?

I've got a PHP page with 2 MySQL statements in various parts of the code. I'm using the generated result sets to set cookie values then call it later. Yet, when I call the cookie data, it does not update the display of the cookie values until after a 2nd refresh. To Better understand, Here's the 3 sections of code:
<?php
include 'functions.php';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$SqlStatement = "SELECT Deceased.PK_Deceased, Deceased.Date_Death, Personal_Info.First_Name, Personal_Info.Last_Name FROM Deceased INNER JOIN Personal_Info ON Personal_Info.PK_Personal_Info = Deceased.FK_Personal_Info WHERE Deceased.FK_Personal_Info = '".$_POST['cboDeceased']."'";
$result = ExecuteSql($SqlStatement);
if(mysqli_num_rows($result) == 1)
{
$row = mysqli_fetch_array($result);
setcookie('deceasedID', $row['PK_Deceased'], time()+360000, '/');
setcookie('deceasedName', ($row['First_Name']." ".$row['Last_Name']), time()+360000, '/');
setcookie('deceasedDoD', $row['Date_Death'], time()+360000, '/');
}
}
?>
This is the code that pulls the data from the postback. I think that this is the part that is incorrect, but I'm not sure.
<tr>
<td width="25%" rowspan="2" align="center">Current User: <?php echo $_COOKIE['username']; ?> </td>
<td width="25%" rowspan="2" align="center">Current Deceased: <?php if(isset($_COOKIE['deceasedName']))echo $_COOKIE['deceasedName']; ?></td>
<td width="50%" rowspan="2" align="center">Deceased Date of Death: <?php if(isset($_COOKIE['deceasedDoD']))echo $_COOKIE['deceasedDoD']; ?></td>
This is the code to load the cookie data into fields and the part that takes the 2nd refresh to display properly.
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<table align="center" width="500" border="0.5">
<tr>
<td width="176" align="right" style="font-weight:bold;">Please select deceased:</td>
<td width="214">
<select name="cboDeceased" id="cboDeceased">
<option>Select...</option>
<?php
$SqlStatement = "SELECT Deceased.PK_Deceased , Personal_Info.First_Name, Personal_Info.Last_Name FROM Deceased INNER JOIN Personal_Info ON Personal_Info.PK_Personal_Info = Deceased.FK_Personal_Info";
$res = ExecuteSQL($SqlStatement);
while($row = mysqli_fetch_array($res))
{
echo "<option value='".$row['PK_Deceased']."'>".$row['First_Name']." ".$row['Last_Name']."</option>";
}
?>
This is the code that passes a variable based on ID to the 1st code block. This part works fine.
function ExecuteSQL($SQL)
{
$con = mysqli_connect("localhost", "root", "", "exec_support_db");
$res = mysqli_query($con, $SQL);
mysqli_close($con);
return $res;
}
Here's the code for the ExecuteSQL function. I know that this isn't the problem.
I think the problem is up above in the 1st code block, but I'm not sure. I've tried everything I can and am now out of ideas. Any help would be appreciated.
Beyond the SQL injection mentioned above by DaveRandom take a look at the php manual on how setcookie works:
http://php.net/manual/en/function.setcookie.php
It mentions specifically the info is injected into the headers, and therefor not available until your next page load. You probably want to do something like
if(isset($_COOKIE['deceasedID']))
{
$deceasedID = $_COOKIE['deceasedID'];
}
else
{
setcookie('deceasedID', $row['PK_Deceased'], time()+360000, '/');
$deceasedId = $row['PK_Deceased'];
}

Update mysql database fields with array php

I'm trying to achieve a multiple update in one submit. I have a table with a number of rows and want to be able to update one field in each row just by tabbing to the next insert box.
My code is thus:-
//start a table
echo '
';
//start header of table
echo '<tr>
<td width="60" align="center"><strong>Lab Item ID</strong></td>
<td width="60" align="center"><strong>Test Suite Name</strong></td>
<td width="60" align="center"><strong>Test Name</strong></td>
<td width="50" align="center"><strong>Result</strong></td>
</tr>';
//loop through all results
while ($row=mysql_fetch_object($sql)) {
//print out table contents and add id into an array and email into an array
echo '<tr>
<td align="center"><input name="id[]" value='.$row->lab_item_id.' readonly> </td>
<td align="center">'.$row->test_suite_name.'</td>
<td align="center">'.$row->test_name.'</td>
<td><input name="test_result[]" type="text" value="'.$row->test_result.'"></td>
</tr>';
}
//submit the form
echo'<tr>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>';
//if form has been pressed proccess it
if($_POST["Submit"])
{
//get data from form
//$name = $_POST['name'];
//$_POST['check_number'] and $_POST['check_date'] are parallel arrays
foreach( $_POST['id'] as $id ) {
$tresult = trim($_POST['test_result']);
$query = "UPDATE tbl_lab_item SET test_result='$tresult' WHERE lab_item_id = '$id'";
//execute query
}
print_r($_POST);
var_dump($tresult);
//redirect user
$_SESSION['success'] = 'Updated';
//header("location:index.php");
}
?>
When I print the $_POST arrays, everything is populating fine, however the variable is Null. I know I can't do a foreach on multiple arrays (at least I don't think I can) so is there some other trick I'm missing please? I can't be far away as the $_Post print has the right data in it.
Incidentally, the whole thing is generated by a query, so I never know how many records I'll have to update.
I've been looking at this (and other) forums, but can't seem to get a solution. I thought I understood arrays, but now I'm beginning to wonder!
edit - it's the $tresult variable that isn't working.
Many thanks,
Jason
Edit Thursday 21st Feb (05:41 UK time)
Thanks for your input everybody. I've solved this one now, and your collective advice helped. The code that finally cracked it is:-
//get data from form
$id1 = $_POST['id'];
$test_result1 = $_POST['test_result'];
foreach ($id1 as $key => $value){
$query = "UPDATE tbl_lab_item SET test_result='$test_result1[$key]' WHERE lab_item_id=$value ";
//execute query
Working through which variables etc were populated and what they were populated with was the key. Back to first principles, isn't it?
Cheers all.
J
Actually, you might get it done by doing a simpler (basic) form of for loop:
//get data from form
//$name = $_POST['name'];
//$_POST['check_number'] and $_POST['check_date'] are parallel arrays
$numberOfData = count($_POST['id']);
for($index = 0; $index < $numberOfData; $index++)
{
$id = $_POST['id'][$index];
$tresult = trim($_POST['test_result'][$index]);
$query = "UPDATE tbl_lab_item SET test_result='$tresult' WHERE lab_item_id = '$id'";
//execute query
}
print_r($_POST);
I hope this helps.
Cheers
change the query like this :
$query = "UPDATE tbl_lab_item SET test_result=$tresult WHERE lab_item_id = $id";
By adding single quotes ' ' you tell it to read is as a String and not to take the value of the var.
Edit
Replace your foreach loop with the following and let me know :
$id1 = $_POST['id'];
$test_result1 = $_POST['test_result'];
foreach( $id1 as $key => $value ) {
$query = "UPDATE tbl_lab_item SET test_result='$test_result1[$key]' WHERE lab_item_id = '$key' ";
}
Problem is that you're telling PHP to build your input fields as arrays, but then treat it as a string later:
<td><input name="test_result[]" type="text" value="'.$row->test_result.'"></td>
^^--- array
$tresult = trim($_POST['test_result']);
^^^^^^^^^^^^^^^^^^^^^--- no array key, so you're assigning the entire array
$query = "UPDATE tbl_lab_item SET test_result='$tresult'
^^^^^^^^^^--- array in string context
trim() expects a string, but you pass in an array, so you get back a PHP NULL and a warning. That null then gets stuffed into your SQL statement, and there's your problem.

Hyperlinks from rows in Mysql Table

The thing is that I have made application form which saves in db. And I want on other page to display just some rows of the mysql table in php table where the first column is hyperlink to the single application as it is in the form. My question is how it can automatically make hyperlinks and pages for each form?
This is my code for now
mysql_connect("host", "user", "password") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());
$data = mysql_query("SELECT * FROM applications ") or die(mysql_error());
echo ' <table width="760" border=1>
<tr>
<th>Заявление<br>От дата:</th>
<th>От/До</th>
<th>Статус</th>
</tr>';
while($info = mysql_fetch_array( $data ))
{
echo '
<tr>
<td>'.$info['today'] .'</td>
<td>От '.$info['data1data'] .'.'.$info['data1mesec'] .'.'.$info['data1god'] .' до '.$info['data2data'] .'.'.$info['data2mesec'] .'.'.$info['data2god'] .' </td>
<td>';
if($info['status'] == 1) {
echo '<img src="Images/approved.jpg" />';
}
else {
echo '<img src="Images/declined.jpg" />';
}
echo ' </td>
</tr> ';
}
echo '</table>';
The result I am trying to get is a table with 3 columns and rows for every application and from the first column of the application I get redirected to a single webpage for that application form and this link to be auto made by code something like "applications.php?id=[application id]"
I don't understand so much but:
<?php
$query = mysql_query("SELECT * FROM applications");
while($t = mysql_fetch_array($query)){
echo ''.$t['name'].'<br/>';
}
?>
Don't know what's the problem.

Gridview like control in php

Im new to php..I had used GridView control in asp.net for Listing records.
Now I want to use a control in php to list the records with checkbox options to select them for deletion and also page enabled. Can anyone guide a beginner on how to do this?
Thanks in advance.
Your idea consists of two things; a table and a php-file that processes the input from the table.
File: table.php
<form method="post" action="process.php">
<table>
<thead>
<tr>
<th>Title</th>
<th>Activate</th>
<th>Delete</th>
</tr>
</thead>
<?php foreach( $records as $record ): ?>
<tr>
<td><?php echo $record['title']; ?></td>
<td><input type="checkbox" name="activate_ids[]" value="<?php echo $record['id']; ?>" /></td>
<td><input type="checkbox" name="delete_ids[]" value="<?php echo $record['id']; ?>" /></td>
</tr>
<?php endforeach; ?>
</table>
</form>
File: process.php
<?php
//Gather the $_POST
$activate_ids = $_POST['activate_ids'];
$delete_ids = $_POST['delete_ids'];
//Let's make sure we only get ints
for($i = 0; $i < count($activate_ids); $i++)$activate_ids[$i] = intval($activated_ids[$i]);
for($i = 0; $i < count($delete_ids); $i++)$delete_ids[$i] = intval($delete_ids[$i]);
//Get the ids
$activate_ids_string = implode(',', $activate_ids);
$delete_ids_string = implode(',', $delete_ids);
//Make sure we don't have '' as a parameter for SQL
if( $activate_ids_string == '' ) $activate_ids_string = 0
if( $delete_ids_string == '' ) $delete_ids_string = 0;
//UPDATE the table
$sql_activate = 'UPDATE Records SET active=1 WHERE id IN (' . $activate_ids_string . ')';
$sql_delete = 'DELETE FROM Records WHERE id IN (' . $delete_ids_string . ')';
//Execute the queries and get the # of affected rows
$aff_rows_activate = mysql_num_rows(mysql_query($sql_activate));
$aff_rows_delete = mysql_num_rows(mysql_query($sql_delete));
//Last but not least, output how it went for both queries
if( $aff_rows_activate === 1 ) echo 'Activated one record.';
else echo 'Activated ' , $aff_rows_activate, ' records.';
if( $aff_rows_delete === 1 ) echo 'Deleted one record.';
else echo 'Deleted ' , $aff_rows_activate, ' records.';
?>
I haven't had a chance to try out the code above, so there might still be a couple of syntax errors in it - however, you should be able to get an idea of what you need to do to achieve the results that you want.
php is different form asp. asp has many controls whcih u can use but php has core function for core funtionlity. to achive ur goal u have to use table put checkbox in the table with ur data in it and use ajax to delete rows from the table or just post the page on checkbox click. but there is no control for this u have to code it urself, u can say php is like c++. and for paging u can use some class which are find here enter link description here

Categories