I have just used my first bit of AJAX to search a MySQL database. This is for a persons name I would normally add a href to the result (which i have) and post to a seprate page to show all the the relevant details, eg address, grade and location. However i was wondering if this is possible staying on the same page. This is what i have so far. ( and yes the CSS will be moving to a seprate page)
<?php
if(!strlen(trim($_SESSION['Unique_Id']))) {
header("Location:roster.php");
exit();
}
?>
<title>Search Roster</title>
<style>
body {
font-family: "Lucida Grande", Verdana, Arial, sans-serif;
font-size: 12px;
}
#results {
color: #fff;
background: #414141;
width: 180px;
max-height: 200px;
padding-left: 4px;
border: 1px solid #000;
overflow-y: scroll;
overflow-x: hidden;
}
a { color: #fff; display: block; }
a:hover { background: #666666; }
</style>
Keyword Search:
<form id="searchform" method="post" onsubmit="return false;"><input autocomplete="off" id="searchbox" name="searchq" onkeyup="sendRequest()" type="textbox">
</form><div id="show_results"></div><script src="config/prototype.js" type="text/javascript">
</script>
<script>
function sendRequest() {new Ajax.Updater('show_results', 'pages/login/search.php', { method: 'post', parameters: $('searchform').serialize() });
}
</script>
<?php include("pages/include/footer.php"); ?>
and the search.php page
<?php
$host="****"; // Host name
$sqlusername="****"; // Mysql username
$sqlpassword="****"; // Mysql password
$db_name="****"; // Database name
$tbl_name="****"; // Table name
mysql_connect("$host", "$sqlusername", "$sqlpassword")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$searchq = $_POST['searchq'];
if(empty($searchq)) {
echo "";
} else {
echo "<div id='results'-->";
//This query searches the name field for whatever the input is.
$sql = "SELECT * FROM USER WHERE Employee LIKE '%$searchq%' OR staff LIKE '%$searchq%'";
echo "<table border='3'>
<tr>
</tr>";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$name = $row['EmployeeName'];
$id=$row['Unique_Id'];
echo "<a href=anotherpage.php?item=".$id."</a>";
echo "$name";
echo "</br>";
}
echo "</div>";
}
?>
You have did mistake in following line of code in "search.php". Also verify other line of code.
echo "<a href=anotherpage.php?item=".$id."</a>";
echo "$name";
Above code should be like as follows :
echo "".$name."";
Related
I am trying to put in a search filter that makes it so you can enter the lock number and it will return just the fields from the phpmyadmin database that has that lock number associated with it. The file name is dataout.php.
<?php
$db_host = 'localhost';
$db_user = 'nick';
$db_pass = 'ramon';
$db_name = 'lockout'; ?>
<link href="lockproject.css" type="text/css" rel="stylesheet">
<input type="text" name="locknumber" placeholder="Enter Lock Number"><br>
<br>
<input type="submit" name="search" value="Submit">
<?php
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Fail to connect to MySQL: ' . mysqli_connect_error());
}
$sql = 'SELECT ID, lock_number, equipment_number, work_order, date_out,
supervisor_out, comments_out, date_in, supervisor_in
FROM form';
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
echo '<table width="60%" align="center">
<thead>
<tr>
<th>ID</th>
<th>Lock Number:</th>
<th>Equipment</th>
<th>Work Order:</th>
<th>Date OUT:</th>
<th>Supervisor Initial OUT:</th>
<th>Comments/Tradesmen:</th>
<th>Date In:</th>
<th>Supervisor Initial in:</th>
</tr>
</thead>
<tbody>';
while ($row = mysqli_fetch_array($query))
{
echo '<tr>
<td>'.$row['ID'].'</td>
<td>'.$row['lock_number'].'</td>
<td>'.$row['equipment_number'].'</td>
<td>'.$row['work_order'].'</td>
<td>'.$row['date_out'].'</td>
<td>'.$row['supervisor_out'].'</td>
<td>'.$row['comments_out'].'</td>
<td>'.$row['date_in'].'</td>
<td>'.$row['supervisor_in'].'</td>
</tr>';
}
echo '
</tbody>
</table>';
mysqli_free_result($query);
mysqli_close($conn);
?>
<a href="http://152.116.203.115/lockcheckin2.php" target='_blank'>Lock
Check
In Form</a>
<a href= "http://152.116.203.115/lockcheckoutbeta.php"
target='_blank'>Lock
Check Out Form</a>
Here is the code for the css file that is attached to it called lockproject.css
{
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
h1 {
border-bottom: 2px solid rgba(255, 255, 255, 0.5);
color: white;
font-weight: 120;
font-size: 36px;
line-height: 30px;
padding-bottom: 20px;
text-align: center;
width: 100%;
}
h3 {
color: #F81B1D
}
td, th {
border: 2px solid #ddd;
padding: 14px;
}
tr:nth-child(odd){background-color: #f2f2f2;}
tr:nth-child(even){background-color: #214CD2;}
th {
padding-top: 14px;
padding-bottom: 14px;
text-align: left;
background-color: #000000;
color: white;
}
body {
background-color: #4D4949;
}
a:link, a:visited {
background-color: #214CD2;
color: white;
padding: 14px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
}
a:hover, a:active {
background-color: blue;
}
This can be solved by using a SQL where statement, a good example is shown here: https://www.w3schools.com/sql/sql_where.asp
By using a GET request in the HTML form, we can get the value from the field and use it in out PHP script. See:
https://www.w3schools.com/php/php_forms.asp
Html file:
This will submit the lock number to the file as a get request
<form action="dataout.php" method="get">
Name: <input type="text" name="lock_number"><br>
<input type="submit">
</form>
</body>
</html>
PHP script:
We get the value associated with the GET request and use it in the query
For protection you should use prepared statements.
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
$sql = "SELECT ID, lock_number, equipment_number, work_order, date_out, supervisor_out, comments_out, date_in, supervisor_in FROM form WHERE lock_number = ?";
$stmt = $this->conn->prepare($sql);
$stmt->bind_param('s', $lock_number);
$stmt->execute();
$stmt->bind_result($result);
while ($stmt->fetch()) {
//This while give back a row at a time.
//This contains only the rows that the WHERE statement gets
}
Edited in light of Patrick Q's and Sam Swift's comments.
What you do is SELECT from the TABLE where the lock number in the table equals the entered input. That's all. Nothing hard about it. Also don't use the die function it's deprecated.
What you're looking for is:
if(isset($_POST['submit'])) {
$lock_number = $_POST['lock_number'];
$sql = 'SELECT id, lock_number, equipment_number, work_order, date_out,
supervisor_out, comments_out, date_in, supervisor_in
FROM form WHERE lock_number = "{$lock_number}",'
}
First you check if the button has peen pressed then put the entered input into a variable then query the database based on it. It will return the wanted row.
You need to do 2 thing:
Put search box in a form tag, submit button should come under form tag.
<form id="search-form" method='POST'>
<input type="text" name="locknumber" placeholder="Enter Lock Number"><br>
<br>
<input type="submit" name="search" value="Submit">
</form>
Now Need to update $sql Query with condition. after $sql query, need to check if lockumber value is coming in post and not empty we have to add condition with query as given below.
$sql = 'SELECT ID, lock_number, equipment_number, work_order, date_out,
supervisor_out, comments_out, date_in, supervisor_in
FROM form';
if (isset($_POST['locknumber']) && !empty($_POST['locknumber'])) {
$sql .= " where lock_number = '" . $_POST['locknumber'] . "'";
}
Hopefully this can help you to resolve your issue. Thanks.
I have a question related to php and html.
I am trying to write in a table from a mysql database.
My question is: Why does it write the text "SEMIFINAL 2" before it writes the table, but in the code the table is written before the text "SEMIFINAL 2"?
I could really use some help. Thanks a lot.
P.S. Here is the code
<html>
<style>
table {
color: #333;
font-family: Helvetica, Arial, sans-serif;
width: 640px;
border-collapse:
collapse; border-spacing: 0;
}
td, th {
border: 1px solid transparent; /* No more visible border */
height: 30px;
transition: all 0.3s; /* Simple transition for hover effect */
}
th {
background: #DFDFDF; /* Darken header a bit */
font-weight: bold;
text-align: center;
}
td {
background: #FAFAFA;
text-align: center;
}
/* Cells in even rows (2,4,6...) are one color */
tr:nth-child(even) td { background: #F1F1F1; }
/* Cells in odd rows (1,3,5...) are another (excludes header cells) */
tr:nth-child(odd) td { background: #FEFEFE; }
tr td:hover { background: #666; color: #FFF; } /* Hover cell effect! */
</style>
<?php
$host="localhost";
$username="root";
$password="";
$db_name="lol";
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("lol") or die("Cannot connect to database");
$query="call semi2";
$results = mysql_query($query);
print('<table align=center>');
print ("<tr>");
echo '<th>First Name</th>';
echo '<th>Last Name</th>';
echo '<th>Victories</th>';
echo "</center>";
$nr_val=0;
if($results === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row=mysql_fetch_row($results)){
echo" <tr>\n";
foreach($row as $value){
echo "<td>$value</td>";
$nr_val++;
}
echo"</tr>";
}
$coln=mysql_num_fields($results);
$nr_inreg=$nr_val/$coln;
echo "<br>";
echo "<center>";
if ($nr_inreg>0)
echo "SEMIFINAL 2";
else
die ("Can't find any recording....");
echo "</center>";
mysql_close();
?>
</html>
You forgot the closure table tag
You have a center closure tag that seems misplaced in your table header
Add the closure table tag closing before outputing your text
I am tryig to make a photo gallery on my website. I have a small problem with making link on images I have in for loop
Since You requested full code here it is:
<html>
<head>
<meta charset="UTF-8">
<title>Fotečky</title>
<style>
.foto{
position: relative;
display: inline-block;
text-align: center;
width: 200px;
border: solid;
margin-left: 6%;
}
#date{
position: relative;
text-align: center;
width: 200px;
}
a { color: #000000; text-decoration: none; }
.menu {
background-color: #FF9933;
height: 10%;
line-height: 300%;
}
</style>
</head>
<body>
<div class="menu">
<center><h2>Upload photo</h2></center>
</div>
<br>
<?php
mb_internal_encoding("UTF-8");
$connect = mysql_connect("","","") or die("Couldn't connect");
mysql_set_charset('utf8',$connect);
mysql_select_db("") or die("Couldn't find db");
$SQLCommand = "SELECT * FROM foto";
$result1 = mysql_query($SQLCommand); $database = array(); $index = 1; // make a new array to hold all your data
while($row1 = mysql_fetch_assoc($result1)) // loop to give you the data in an associative array so you can use it however.
{
$database[$index] = $row1;
$index++;
}
for ($i=1; $i < count($database); $i++) {
echo '<a href="photo.php?id='.$database[$i]['id'].'">';
echo '<div class="foto">';
echo '<img title="'.$database[$i]['description'].'" alt="'.$database[$i]['description'].'" src="data:image/jpg/png/jpeg;base64,'.base64_encode( $database[$i]['image'] ).'" width="200px"/>';
echo "<div id='date'>".$database[$i]['uploaded']."</div>";
echo '</div>';
echo '</a>';
if ((($i % 4) == 0) && ($i != 0)) {
echo '<br><br>';
}
}
?>
</body>
I want to display image one by one and be able to click on them -> link that brings me to photo.php?id= with id of that image. (id is from 1 to n)
db sructure:
enter image description here
i have table created inside php with css but the table isn't complete as you see in the photo from the download part. its coming half in the download part.
please someone look to my code and let me know where i gone wrong.
thank you.
my css code
<style type='text/css'>
.container3 {
float:left;
width:100%;
/*background:green;*/
overflow:hidden;
position:relative;
}
.container2 {
float:left;
width:100%;
background:#FFA500;
position:relative;
right:45%;
}
.container1 {
float:left;
width:100%;
/*background:red;*/
position:relative;
right:40%;
}
.col1 {
float:left;
width:26%;
position:relative;
left:87%;
bottom:-200px;
font-size:20px;
text-align:left;
overflow:hidden;
height:570px;
}
.col2 {
float:left;
width:50%;
position:relative;
left:90%;
overflow:hidden;
}
.col3 {
float:left;
width:26%;
position:relative;
left:80%;
overflow:hidden;
}
.footer {
border:1px solid orange;
position: relative;
padding:0px;
margin-top:-5px;
font-size:15px;
}
.signout {
position: absolute;
left: 5px;
bottom: 150px;
width: 130px;
clear: both;
font-size:20px;
text-align:center;
}
.tableClass{
margin-bottom:60px;
}
</style>
<style>
table
{
border-collapse:collapse;
}
table, td, th
{
border:1px solid black;
}
</style>
<style>
table,td,th
{
border:1px solid black;
}
td
{
text-align:center;
}
</style>
<style>
table,td,th
{
border:1px solid black;
}
table
{
width:100%;
}
th
{
height:50px%;
}
</style>
my php code
<div id="header" style="background-color:#FFA500;">
<h1 style="margin-bottom:0;">Wellcome To Balhaf Services Customer Reports</h1>
<div class="container3 ">
<div class="container1 ">
<div class="container2 ">
<div class="col1">
View Report <br />
View Chart <br />
</div>
<?php
$username = $_POST["username"];
$password = $_POST["password"];
// Connect to the database
$dbLink = new mysqli('localhost', 'sqldata', 'sqldata', 'balhaf');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
//for mysql injection (security reasons)
$username = mysqli_real_escape_string($dbLink, $username);
$password = mysqli_real_escape_string($dbLink, $password);
mysqli_select_db($dbLink,"balhaf2");
//checking if such data exist in our database and display result
$login = mysqli_query ($dbLink,"select * from users where USERNAME = '$username' and
PASSWORD = '$password'");
if(mysqli_num_rows($login) == 1) {
// Fetch the file information
$query = "select * from users WHERE username = '".$dbLink->escape_string($username)."'";
$result = $dbLink->query($query);
$company = false;
//Now get the result information
$row = $result->fetch_object(); //will store the record in $row
//Access what you need
if($row) {
$company = $row->company; //variable name should match the field name in your database
echo $company; //See if you get the value stored in the database
}
mysqli_select_db($dbLink,"balhaf");
// Query for a list of all existing files
$sql = "SELECT id, name, mime, size, created FROM $company";
$result = $dbLink->query($sql);
// Check if it was successfull
if($result) {
// Make sure there are some files in there
if($result->num_rows == 0) {
echo '<p>There are no files in the database</p>';
}
else {
// Print the top of a table
echo '<div class="col2">';
echo '<div align="center">';
echo '<H2 align="center"> Report Table</H></div>';
echo '<table border="1" align="center"class="tableClass">
<tr>
<td><b>Name</b></td>
<td><b>Mime</b></td>
<td><b>Size (bytes)</b></td>
<td><b>Created</b></td>
<td><b>Download</b></td>
</tr>';
// Print each file
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>{$row['name']}</td>
<td>{$row['mime']}</td>
<td>{$row['size']}</td>
<td>{$row['created']}</td>
<td><a style='text-decoration:none;'href=' get_file_work.php?id={$row['id']}&company=$company'>Download</a></td>
</tr>";
}
// Close table
echo '</table>';
echo '</div>';
}
// Free the result
$result->free();
}
else
{
echo 'Error! SQL query failed:';
echo "<pre>{$dbLink->error}</pre>";
}
// Close the mysql connection
$dbLink->close();
}
else {
echo "worng user"."</br>";
}
?>
<div class="col3">
</div>
</div>
</div>
<div class="signout">
<a style='text-decoration:none;' href= "index.html">Sign Out </br></a>
</div>
<div class="footer" style="background-color:#FFA500;clear:both;text-align:center;">
Copyright balhaf services 20103-2014</div>
</div>
Your container3 is cutting off the display of it's contents with "overflow:hidden;"
You could switch it to:
.container3 {
float:left;
width:100%;
/*background:green;*/
overflow:auto;
position:relative;
}
Or if you don't want to bleed off the edge you could either replace the filename with a download link, something like "view document". Or you could limit the number of characters allowed to show in the table cell. OR you could look into the word-break property (not reliable across all browsers) - see the link below for documentation.
W3Schools - Word-break
I have a question for you to upgrade my knowledge.
I am trying to create an inline editing page, the data are stored in a database.
In the table "content" I create 2 fields for testing purpose, the "id" and the "text" field.
If I want to modify the field with the "id=25" or id=X, I know how to do it manually, just specify in the MySQL Query "WHERE id=25", but if I have a list of 1000 entries, how can I modify the query to get the ID on the fly?
Here is the code, I am playing on:
index.php file
<style>
body {
font-family: Helvetica,Arial,sans-serif;
color:#333333;
font-size:13px;
}
h1{
font-family: Georgia, Times, serif;
font-size: 28px;
}
a{
color: #0071D8;
text-decoration:none;
}
a:hover{
text-decoration:underline;
}
:focus {
outline: 0;
}
#wrap{
width: 500px;
margin:0 auto;
overflow:auto;
}
#content{
background: #f7f7f7;
border-radius: 10px;
}
#editable {
padding: 10px;
}
#status{
display:none;
margin-bottom:15px;
padding:5px 10px;
border-radius:5px;
}
.success{
background: #B6D96C;
}
.error{
background: #ffc5cf;
}
#footer{
margin-top:15px;
text-align: center;
}
#save{
display: none;
margin: 5px 10px 10px;
outline: none;
cursor: pointer;
text-align: center;
text-decoration: none;
font: 12px/100% Arial, Helvetica, sans-serif;
font-weight:700;
padding: 5px 10px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
color: #606060;
border: solid 1px #b7b7b7;
background: #fff;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#ededed));
background: -moz-linear-gradient(top, #fff, #ededed);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#ededed');
}
#save:hover
{
background: #ededed;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#dcdcdc));
background: -moz-linear-gradient(top, #fff, #dcdcdc);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#dcdcdc');
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$("#save").click(function (e) {
var content = $('#editable').html();
$.ajax({
url: 'save.php',
type: 'POST',
data: {
content: content
},
success:function (data) {
if (data == '1')
{
$("#status")
.addClass("success")
.html("Data saved successfully")
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
}
else
{
$("#status")
.addClass("error")
.html("An error occured, the data could not be saved")
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
}
}
});
});
$("#editable").click(function (e) {
$("#save").show();
e.stopPropagation();
});
$(document).click(function() {
$("#save").hide();
});
});
</script>
</head>
<body>
<div id="wrap">
<div id="status"></div>
<div id="content">
<div id="editable" contentEditable="true">
<?php
//get data from database.
include("db.php");
$sql = mysql_query("select * from content");
$row = mysql_fetch_array($sql);
echo $row['id'];
echo "<br />";
echo $row['text'];
?>
</div>
<button id="save">Save</button>
</div>
</div>
</body>
And here is the save.php file:
include("db.php");
$content = $_POST['content']; //get posted data
$content = mysql_real_escape_string($content); //escape string
$sql = "UPDATE content SET text = '$content' WHERE id = '$id' ";
if (mysql_query($sql))
{
echo 1;
}
I know that this could be a stupid question but I am a newbie.
Thank you in advance for the help.
UPDATE:
thanx to Luis I fixed my old problem but I don't know why if I put all the code in a while only the "Save" button of the first entry is working good, the rest not, any hint?
At the moment I am testing only "description_text".
Here is the "while" code:
<?php
/////////// Now let us print the table headers ////////////////
$query =" SELECT * FROM gallery ORDER BY id DESC ";
$result = mysql_query($query) or die(mysql_error());
echo "<div style='width: 100%; text-align: center;'>";
echo "<table style='margin: auto auto;'>";
echo "<tr><th>ID</th><th>Image</th><th>Category</th><th>Description</th><th>Added on</th></tr>";
while($ordinate = mysql_fetch_array($result))
{
$id = $ordinate['id'];
$img_name = $ordinate['img_name'];
$category = $ordinate['category'];
$description_text = $ordinate['description_text'];
$insert_datetime = $ordinate['insert_datetime'];
echo "<tr><td style='width: 20px;'>".$id."</td><td style='width: 210px;'><img src='../../upload/content/uploaded_images/". $img_name ."' width='200px'></td><td style='width: 100px;'>".$category."</td><td style='width: 100px;'><div id='status'></div><div id='content'><div id='editable' contentEditable='true'>".$description_text."</div><button id='save'>Save</button></div></td><td style='width: 100px;'>".$insert_datetime."</td></tr>";
}
echo "</table><br /><br /></div>";
?>
on index.php move this part of code to the beginning, so you can use same vars in the rest of the script.
<?php
//get data from database.
include("db.php");
$sql = mysql_query("select * from content");
$row = mysql_fetch_array($sql);
// echo $row['id']; but keep this ones in its original place inside their <%php %> tags
// echo "<br />";
// echo $row['text'];
?>
Later in the ajax call, insert this PHP lines:
data: {
content: content
<?php
echo ", id: ".$row['id'];
echo ", token: '".md5('my SALT text'.(int)$row['id'])."'"; // strongly!!! recomended, not mandatory
?>
},
and on save.php
$id = (int)$_POST['id']; // (int) sanitizes id
$token = $_POST['token'];
if(md5('my SALT text'.$id)!=$token) die(); // or whatever but do not execute update
// perhaps echo 0; die();
// ... rest of your code ....
$sql = "UPDATE content SET text = '$content' WHERE id = $id"
the token, prevents the risk that someone uses your save.php as a way to inject whatever on every post on the table.
At least, an advice: use mysqli_query (notice the i) instead of mysql_query as this last is deprecated. Also, but with more diferences, you can use PDO
Instead of simply echoing the $row['id'], echo it inside an HTML element with specific id, so that it can be accessed from jQuery and can be posted.
<span id="idfield"><?php echo $row['id']; ?></span>
<button id="save">Save</button>
</div>
Then, inside the javascript :
$("#save").click(function (e) {
var content = $('#editable').html();
var id = $('#idfield').html();
Use it as a parameter in POST:
$.ajax({
url: 'save.php',
type: 'POST',
data: {
content: content,
id: id
},