Hello Please forgive me if I'm not asking this right. I have the following code.
<?php
//Connect to mysql server
include ("Data.php");
if (!$con) {
die ("connection error". mysqli_connect_error());
}
$sql1 = "SELECT * FROM PMList where AssetNum= '$AssetNum' and Plant= '$Plant';";
$result = mysqli_query($con, $sql1) or die(mysqli_error($con));
if ($result->num_rows > 0)
$count = 0;
$Task = 1;
while($row = mysqli_fetch_array($result))
{
$Task++;
echo "<td bgcolor='#D8D8D8' align='Left'>";
echo "<font size='2'>";
echo $row['Task$Task'];
echo " </font></td>";
echo "<td bgcolor='#D8D8D8'><input type='radio' name='Task$Task' value='Yes'>Yes";
echo " <input type='radio' name='Task$Task' value='No'>No";
echo "<tr border='0'>";
}
while ($count++ < 16) {
}
$con->close();
?>
What I am trying to do is add the $task value to the echo $row['Task$Task']; So that the value turns to task1 then task2 , task3 ect. There can be up to 15 tasks. I'm close just not sure on where I'm messing up. Any help would be great. been stuck on this one for awhile now. Thank you in advance!!
OK now this is what I have its displaying almost correctly.
$sql1 = "SELECT * FROM PMList where AssetNum= '$AssetNum' and Plant= '$Plant';";
$result = mysqli_query($con, $sql1) or die(mysqli_error($con));
if ($result->num_rows > 0)
$count = 0;
$Task = 1;
while($row = mysqli_fetch_assoc($result))
do
{
echo "<td bgcolor='#D8D8D8' align='Left'>";
echo "<font size='2'>";
echo $row['Task'.$Task];
echo " </font></td>";
echo "<td bgcolor='#D8D8D8'><input type='radio' name='Task$Task' value='Yes'>Yes";
echo " <input type='radio' name='Task$Task' value='No'>No";
echo "<tr border='0'>";
$Task++;
}
while ($count++ <= 13);
$con->close();
?>
Now it is looping however, If the task is empty I need to not echo the radio buttons and stop where it ends. capture. Thank you guys your all awesome!! How do I add a if statement thst can see if the $row['Task'.$Task]; is null then stop the loop?
You should use " to make string with variable or use . dot to concatenation , either
echo $row["Task$Task"];
Or
echo $row['Task'.$Task];
Note(This is just for example and prone to sql injection you should check
how to Use PDO's and Sanitize php input
<?php
//Connect to mysql server
include ("Data.php");
if (!$con) {
die ("connection error". mysqli_connect_error());
}
$sql1 = "SELECT * FROM PMList where AssetNum= '$AssetNum' and Plant= '$Plant';";
$result = mysqli_query($con, $sql1) or die(mysqli_error($con));
if ($result->num_rows > 0)
$count = 0;
$Task = 1;
$rows = mysqli_fetch_array($result)
foreach($rows as $row )
{
$Task++;
echo "<td bgcolor='#D8D8D8' align='Left'>";
echo "<font size='2'>";
echo $row["Task".$row["id"]];
echo " </font></td>";
echo "<td bgcolor='#D8D8D8'><input type='radio' name='$row["Task".$row["id"]]' value='Yes'>Yes";
echo " <input type='radio' name='$row["Task".$row["id"]]' value='No'>No";
echo "<tr border='0'>";
}
$con->close();
?>
or
<?php
//Connect to mysql server
include ("Data.php");
if (!$con) {
die ("connection error". mysqli_connect_error());
}
$sql1 = "SELECT * FROM PMList where AssetNum= '$AssetNum' and Plant= '$Plant';";
$result = mysqli_query($con, $sql1) or die(mysqli_error($con));
if ($result->num_rows > 0)
$count = 0;
$Task = 1;
while($row = mysqli_fetch_assoc($result))
{
$Task++;
echo "<td bgcolor='#D8D8D8' align='Left'>";
echo "<font size='2'>";
echo $row["Task".$row["id"]];
echo " </font></td>";
echo "<td bgcolor='#D8D8D8'><input type='radio' name='$row["Task".$row["id"]]' value='Yes'>Yes";
echo " <input type='radio' name='$row["Task".$row["id"]]' value='No'>No";
echo "<tr border='0'>";
}
$con->close();
?>
Related
I want to add loop to my sql query so that all the data from the table gets updated at one click. Right now only the last row is getting updated.
<?php
include_once 'db_connect.php';
if(isset($_POST['btn-signup']))
{
$PersonID = mysql_real_escape_string($_POST['PersonID']);
$FirstName = mysql_real_escape_string($_POST['FirstName']);
$Status = mysql_real_escape_string($_POST['Status']);
$Date = mysql_real_escape_string($_POST['Date']);
$uname = trim($uname);
$email = trim($email);
$upass = trim($upass);
// email exist or not
$query = "SELECT Date FROM status WHERE Date='$Date'";
$result = mysql_query($query);
$count = mysql_num_rows($result); // if email not found then register
if($count == 0){
if(mysql_query("INSERT INTO status(PersonID,FirstName,Status, Date) VALUES('$PersonID','$FirstName','$Status','$Date')"))
{
?>
<script>alert('successfully Added ');</script>
<?php
}
else
{
?>
<script>alert('error while registering you...');</script>
<?php
}
}
else{
?>
<script>alert('Sorry Attendence already taken ...');</script>
<?php
}
}
echo "<!DOCTYPE html>\n";
echo "<html>\n";
echo "<head>\n";
echo " <meta charset=\"utf-8\">\n";
echo " <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n";
echo " <title>Attendance</title>\n";
echo "</head>\n";
echo "<body>\n";
echo " \n";
echo "\n";
echo "\n";
include_once 'dbconnect.php';
$query = "SELECT * FROM attandance ";
$result = mysql_query($query);
echo "<h2>Mark Attendance</h2>\n";
echo "<form method=\"POST\" action=\"\">\n";
echo "<table border=\"2\">\n";
echo " <tr>\n";
echo " <th>PersonId</th>\n";
echo " <th>First Name</th>\n";
echo " <th>Status</th>\n";
echo " <th>Date</th>\n";
echo " </tr>\n";
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$PersonID=$row['PersonID'];
$FirstName=$row['FirstName'];
echo "<td> <input type=\"text\" name=\"PersonID\" value=\" $PersonID\"></td>\n";
echo "<td> <input type=\"text\" name=\"FirstName\" value=\" $FirstName\"></td>\n";
echo "<td><select name=\"Status\">\n";
echo " <option value=\"Present\">Present</option>\n";
echo " <option value=\"Absent\">Absent</option>\n";
echo " </select></td>\n";
echo "<td> <input type=\"date\" name=\"Date\" value=\" $Date\"></td>\n";
echo "</tr>\n";
}
echo " </table>\n";
echo "<input id=\"button\" type=\"submit\" name=\"btn-signup\" value=\"Mark\">\n";
echo "</form>\n";
echo "\n";
echo "\n";
echo "<a href='sheet.php'>Attendence Sheet</a>\n";
echo "</body>\n";
echo "</html>\n";
echo "\n";
?>
I am confused as i have used loop in the 2nd part to get value from the database and now i want to use loop to add those value in the database table. How can i add the code to the Insert SQL query in the first part of my code.
I have two forms on a page. When I run the first, it works as intended, but the second, despite having different form id and all the elements being named, will not (it attempts to run the first form, I think, but with no elements being posted it will return no result).
The second form is in the "Roles" section.
Here is the code - any help is appreciated!
/***** Section: Rights *****/
echo '
<!-- div: Edit -->
<div id="dashboardPanelWrapper">
<div id="sectionArrow"></div>
<div id="dashboardPanelTitle">User rights and privileges</div>
<div id="dashboardPanelContent">';
echo "<div id='DV_simple_wrapper_wide'>";
echo "<table width='60%'><tr><th>Role</th><th>Staff</th><tr>";
$query = "SELECT DISTINCT rightName FROM ".$dbName.".rights WHERE siteLimit='gpvwc' AND rightName!='ADMIN' ORDER BY rightName ASC";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$role=$row[0];
echo "<tr><td>$role</td><td>";
// $query2= "SELECT userId FROM ".$dbName.".rights WHERE rightName='$role' AND siteLimit='gpvwc'";
$query2 = "SELECT CONCAT (u.firstName, ' ',u.lastName) AS username, r.head FROM ".$dbName.".rights r LEFT JOIN ".$dbName.".users u ON r.userId=u.id WHERE r.rightName='$role' AND r.siteLimit='gpvwc' ORDER BY r.head DESC, username ASC";
$result2 = mysql_query($query2);
while ($row = mysql_fetch_row($result2)) {
$name=$row[0];
$head=$row[1];
if ($head=='1') { $name="<b>$name, </b>"; }
if ($head=='0') { $name="$name, "; }
echo "$name";
}
echo "</td></tr>";
}
echo "</table>";
echo "<form id='1' action='' method='post'>";
$usersAsArray = $user->listUsers($banned=false);
echo '<div id="defButtonWrapperH">';
echo '<select id="DriverAppealEvent" class="defSelectV" style="min-width: 70px; margin-bottom: 10px;" onchange="submitTarget(this.value);">';
echo '<option value="0">--</option>';
foreach ($usersAsArray as $key => $value) {
echo '<option value="'.$key.'"';
if (isset($target) && $target == $key)
echo 'selected';
echo '>'.$value.'</option>';
}
echo '</select>';
echo '</div>';
echo '<p> </p>';
echo '<p> </p>';
$userToEdit = false;
if ($target) {
$userToEdit = $user->userToView($target);
// Check if any rights given for this user and update form if any
$query = "SELECT u.*, r.rightName, r.countryLimit, r.siteLimit, r.isActive, r.head FROM ".$dbName.".users u
LEFT JOIN ".$dbName.".rights r ON r.userId=u.id WHERE u.id=".$target;
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($row['rightName'] != '') {
$userToEdit['rights'][] = array(
'rightName' => $row['rightName'],
'rightCountryLimit' => $row['countryLimit'],
'rightSiteLimit' => $row['siteLimit'],
'rightIsActive' => $row['isActive'],
'rightHead' => $row['head']
);
}
}
mysql_free_result($result);
// If the user has rights then write a table with all them plus options to revoke
if (!empty($userToEdit['rights'])) {
drawUserRightsTable($userToEdit);
}
echo "</form>";
// Draw selector with rights here so we can add new rights to this user
$useradd=$userToEdit['id'];
echo "<form id='addadmin' action='$RKP/kernel/lib/php_lib/action/AC_Admins.php?op=add&user=$useradd' method='post'>";
echo "Role: <select name='role'>";
$query = "SELECT DISTINCT rightName FROM ".$dbName.".rights WHERE rightName!='ADMIN' ORDER BY rightName ASC";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$righttoadd=$row[0];
echo "<option value='$righttoadd'>$righttoadd</option>";
}
echo "</select></br>";
echo "Head: <input type='radio' name='head' value='0' checked> No <input type='radio' name='head' value='1'> Yes";
echo "<p> </p>";
MODW_Buttons_Button(Normal,Normal,Normal,Normal,None,$RKP,$id,BGenSu,$intern,$intcont);
echo "</form>";
//echo '<pre>';print_r($userToEdit);echo '</pre>';
}
echo "</div>";
echo ' </div>
</div>';
/***** Section: Roles *****/
echo '
<!-- div: Edit -->
<div id="dashboardPanelWrapper">
<div id="sectionArrow"></div>
<div id="dashboardPanelTitle">Disciplinary Committee Roles</div>
<div id="dashboardPanelContent">';
echo "<div id='DV_simple_wrapper_wide'>";
echo "<table width='60%'><tr><th>Series</th><th>Staff</th><th> </th><tr>";
$query = "SELECT id, compName FROM ".$dbName.".competitions WHERE active='1' AND id!='10' ORDER BY id ASC";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$compid=$row[0];
$compName=$row[1];
echo "<tr><td><b>$compName</b></td><td>";
// $query2= "SELECT userId FROM ".$dbName.".rights WHERE rightName='$role' AND siteLimit='gpvwc'";
$query2 = "SELECT CONCAT (u.firstName, ' ',u.lastName) AS username, r.role, u.id, r.series FROM ".$dbName.".DC_roles r LEFT JOIN ".$dbName.".users u ON r.user=u.id WHERE r.series='$compid' ORDER BY username ASC";
$result2 = mysql_query($query2);
while ($row = mysql_fetch_row($result2)) {
$name=$row[0];
$role=$row[1];
$userid=$row[2];
$seriesid=$row[3];
if ($role=='1') { $name="<i>$name</i>"; }
if ($role=='0') { $name="$name"; }
echo "$name <a href='$RKP/kernel/lib/php_lib/action/AC_Admins.php?op=DelDCRights&user=$userid&comp_id=$seriesid'><b>X</b></a></br>";
}
echo "</td></tr>";
}
echo "</table>";
echo "</div>";
echo "<form id='dcroles' action='$RKP/kernel/lib/php_lib/action/AC_Admins.php?op=AddDCRights' method='post'>";
echo "User: <select id='userDC' name='userDC'>";
$query1 = "SELECT id, firstName, lastName FROM ".$dbName.".users ORDER BY lastName ASC, firstName ASC";
$result1 = mysql_query($query1);
while ($row = mysql_fetch_row($result1)) {
$DCuserId=$row[0];
$DCfirstName=$row[1];
$DClastName=$row[2];
echo "<option value='$DCuserId'>$DClastName, $DCfirstName</option>";
}
echo "</select></br>";
echo "</br>";
echo "Series: <select id='seriesDC' name='seriesDC'>";
$query = "SELECT id, compName FROM ".$dbName.".competitions WHERE active='1' AND id!='10' ORDER BY id ASC";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$DCcompId=$row[0];
$DCcompName=$row[1];
echo "<option value='$DCcompId'>$DCcompName</option>";
}
echo "</select></br>";
echo "Third Checker: <input type='radio' id='head' name='head' value='0' checked> No <input type='radio' name='head' value='1'> Yes</br>";
echo "<input type='submit' value='Submit'>";
echo "</form>";
i would like to know how can i make a multiple search criteria with 2 or more textboxes and only one submit button.
my script is:
$sql = "select * from wp_studenti ";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .= " WHERE nume= '{$search_term}' ";
}
$query = mysql_query($sql) or die (mysql_error());
echo "<form name ='search_form' method='POST' action='search.php'>";
echo "<center><h3>Cauta:</h3> <input type='text' name='search_box' />";
echo "<input type='submit' name='search' value='Cauta' /></center>";
echo "</form>";
and my results page that shows after search page:
$sql = "select * from wp_studenti ";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .= "WHERE nume= '{$search_term}'";
}
echo "<center>\n";
echo "<table border='1'>";
echo "<thead>";
echo "<tr><th>Id</th>";
echo "<th>Nume</th>";
echo "<th>Localitate</th>";
echo "<th>Judet</th>";
echo "<th>Sector Financiar</th>";
echo "<th>Link</th></tr>";
echo "</thead>";
$rst = mysql_query($sql);
while($a_row = mysql_fetch_assoc($rst)) {
echo "<tr>";
echo "<td>"; echo $a_row['id']; echo "</td>";
echo "<td>"; echo $a_row['nume']; echo "</td>";
echo "<td>"; echo $a_row['localitate']; echo "</td>";
echo "<td>"; echo $a_row['judet']; echo "</td>";
echo "<td>"; echo $a_row['sector_financiar']; echo "</td>";
echo "<td>"; echo "<a href='results.php?id={$a_row['id']}'>{$a_row['link']}</a>" ; echo "</td>";echo "</tr>";
echo "</table>";
$sql = "select * from wp_studenti ";
if (isset($_POST['search'])) {
$search_term_by_Cauta = mysql_real_escape_string($_POST['search_box_1']);
$search_term_by_localitate = mysql_real_escape_string($_POST['search_box_2']);
//If you want both search mandatory, use "AND" Operator otherwise use "OR". If you want approximate search use "LIKE" Operator in bellow SQL
$sql .= " WHERE nume= '{$search_term_by_Cauta }' OR localitate = '{$search_term_by_localitate }' ";
}
$query = mysql_query($sql) or die (mysql_error());
echo "<form name ='search_form' method='POST' action='search.php'>";
echo "<center><h3>Cauta:</h3> <input type='text' name='search_box_1' />";
echo "<h3>localitate:</h3> <input type='text' name='search_box_2' />";
echo "<input type='submit' name='search' value='Cauta' /></center>";
echo "</form>";
Well you need another search box:
echo "<center><h3>Cauta:</h3> <input type='text' name='search_box1' /><input type='text' name='search_box2' />";
And you need to use that value in your SQL:
if (isset($_POST['search'])) {
$search_term1 = mysql_real_escape_string($_POST['search_box1']);
$search_term2 = mysql_real_escape_string($_POST['search_box2']);
$sql .= " WHERE nume= '{$search_term1}' OR nume= '{$search_term2}'";
}
But you will have to do some thinking about how the search should work, is it supposed to match exactly one OR the other? If you want the text to contain instead of exactly match, you can use the syntax nume LIKE '%searchword%'
Use mysqli instead of mysql, which is depreciated. By PHP, something like this;
<form method='post'>
<input type='hidden' name='srch' val='1'>
Search Type1: <input type='text' name='s1'>
<br>
Search Type2: <input type='text' name='s2'>
<button>Submit</button>
</form>
<?php
if(isset($_POST['srch']))
{
if(!empty($_POST['s1']))$search = $_POST['s1'];
else if(!empty($_POST['s2']))$search = $_POST['s2'];
else die ('No criteria entered');
rest of your code...
}
?>
Also see functions like mysqli_real_escape for security reasons.
Hi Im creating a multiple search form using PHP,HTML,SQL with the use of functions, for example I have 3 search fields Firstname, lastname and email. I would let the user input from any of those, therefore i would be needing the if else statement, but to be able to satisfy all conditions it would take a lot of if else, so i think of using a function to output the table and place it inside the if else after the query on the database. But it seems that it could not be able to search in the database if I do it like this it outputs "0 results", but if i remove the function and place it on the end of my script I am able to search in the db but it could not detect my else condition which is "You have not yet entered any values"
function checkres()
{
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
if (!empty($sfname) && empty($slname) && empty($semail) )
{
$sql = "select * from Userlist where FirstName LIKE '%". $sfname ."%'" ;
checkres();
}
else if (!empty($sfname) && !empty($slname) && empty($semail))
{
$sql = "select * from Userlist where FirstName LIKE '%". $sfname ."%' AND LastName LIKE '%". %slname. "%'";
checkres();
}
else
{
echo "You have not yet entered any values ";
}
mysqli_close($conn);
?>
This is the new one
<form method="post" action="#" id="searchform">
First Name:<br>
<input type="text" name="fname">
<br>Last Name:<br>
<input type="text" name="lname">
<br>Email: <br>
<input type="text" name="email">
<br>
<input type="submit" name="submit" value="Search">
</form>
<?php
$sfname = $_POST["fname"];
$slname = $_POST["lname"];
$semail = $_POST["email"];
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
function checkres()
{
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
if(!empty($sfname) || !empty($slname) || !empty($semail)){
$emailQueryPart = !empty($semail) ? "Email LIKE '%$semail%'" : "";
$lastnameQueryPart = !empty($slname) ? "LastName LIKE '%$slname%'" : "";
$firstnameQueryPart = !empty($sfname) ? "FirstName LIKE '%$sfname%'" : "";
$arr = array($emailQueryPart, $lastnameQueryPart,$firstnameQueryPart);
$sql = "select * from Userlist";
for($i = 0; $i < count($arr); $i++){
if(!empty($arr[$i])){
if($i > 0){
$sql.= " AND ".$arr[$i];
}else{
$sql.= " WHERE ".$arr[$i];
}
}
}
}else{
echo "You must enter at least one value";
}
checkres();
mysqli_close($conn);
?>
You have a few errors:
$sql = "select * from Userlist where FirstName LIKE '%". $sfname ."%' AND LastName LIKE '%". %slname. "%'";
You have %slname instead of $slname.
Another mistake is in the program flow. Your else condition, which is saying :"You have not yet entered any values" will be reached in two cases:
When all fields are left blank
When all fields are filled with values.
You don't want that. You have to improve your logic, and build a query based on that, and that can be done like this:
function checkres()
{
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
if(!empty($sfname) || !empty($slname) || !empty($semail)){
$emailQueryPart = !empty($semail) ? "Email LIKE '$semail'" : "";
$lastnameQueryPart = !empty($slname) ? "LastName LIKE '%$slname%'" : "";
$firstnameQueryPart = !empty($sfname) ? "FirstName LIKE '%$sfname%'" : "";
$arr = array($emailQueryPart, $lastnameQueryPart,$firstnameQueryPart);
$sql = "select * from Userlist";
for($i = 0; $i < count($arr); $i++){
if(!empty($arr[$i])){
if($i > 0){
$sql.= " AND ".$arr[$i];
}else{
$sql.= " WHERE ".$arr[$i];
}
}
}
}else{
echo "You must enter at least one value";
}
checkres();
mysqli_close($conn);
?>
What you do is in my opinion a little bit confusing (and a little bit odd n terms of the program's flow structure).
You can simply use an array of variables for your input fields and then loop through the array to generate your SQL statement. So your HTML form would look like this:
<form method="post" action="#" id="searchform">
First Name:<br />
<input type="text" name="queryArray[FirstName]" />
<br />Last Name:<br />
<input type="text" name="queryArray[LastName]" />
<br />Email:<br />
<input type="text" name="queryArray[Email]" />
<br />
<input type="submit" name="submit" value="Search" />
</form>
A more clear structure would be if you define these 2 functions, which of course can be placed anywhere in your PHP code block:
function createSql($queryArray) {
if (is_array($queryArray)) {
$sql = null;
foreach ($queryArray as $key => $value) {
if ($value != null ) {
$addQuery = "`".$key."` LIKE '%".$value."%'";
if ($sql == null)
$sql = "SELECT * FROM `Userlist` WHERE ".$addQuery;
else
$sql = $sql." AND ".$addQuery;
}
return $sql;
}
}
function checkres($sql) {
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
die("Connection failed: " . mysqli_connect_error());
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0) {
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else
echo "0 results";
// Close connection
mysqli_close($conn);
}
Finally you will have to call the functions according to user activity:
if ($_POST != null) {
$sql = createSql($_POST[queryArray]);
checkres($sql);
}
An example how the SQL generation works is listed here
I'm having a problem to upload images using a form. This is my form code :
<?php
echo '<table width="70%">';
echo '<tr>';
echo '<td>Add Promotion</td>';
echo '</tr>';
echo "<form action='addpromotion_post.php' method='post' enctype='multipart/form-data' name='form1' id='form1'>";
echo '<tr>';
echo "<td> </td>";
echo '</tr>';
echo '<tr>';
echo "<td>Promotion :</td>";
echo "<td><textarea name='promotion1' rows='2'></textarea></td>";
echo '</tr>';
echo '<tr>';
echo "<td>Valid From :</td>";
echo "<td><input type='text' size='40' name='validfrom1' value='promotion' /></td>";
echo '</tr>';
echo '<tr>';
echo "<td>Add Picture :</td>";
echo "<td><input type='file' name='pic1' id='pic1' /></td>";
echo '</tr>';
echo '<tr>';
echo "<td>Add Picture :</td>";
echo "<td><input type='file' name='pic2' id='pic2' /></td>";
echo '</tr>';
echo '<tr>';
echo "<td>Add Picture :</td>";
echo "<td><input type='file' name='pic3' id='pic3' /></td>";
echo '</tr>';
echo '<tr>';
echo "<td> </td>";
echo '</tr>';
echo'<tr>
<td colspan="3" align="center"><input type="submit" name="button" id="button" value="Submit" /></td>
</tr>
</table>
</form>';
This is my post code :
<?php
//session_start();
include_once("connection.php");
$promotion= $_POST["promotion1"];
$validfrom= $_POST["validfrom1"];
$promotion= mysql_real_escape_string($promotion);
$validfrom= mysql_real_escape_string($validfrom);
$sql = "insert into promotion(proid, promotion, validfrom) values ('', '$promotion', '$validfrom')";
mysql_query($sql) or die ("Error in query: $sql");
$lastid=mysql_insert_id();
$file = "slider_imagesClient/".$lastid."/";
mkdir($file);
$pic1 = $_FILES['pic1']['name'];
$pic2 = $_FILES['pic2']['name'];
$pic3 = $_FILES['pic3']['name'];
print_r($pic1);
$ext1 = pathinfo($pic1,PATHINFO_EXTENSION);
$ext2 = pathinfo($pic2,PATHINFO_EXTENSION);
$ext3 = pathinfo($pic3,PATHINFO_EXTENSION);
//$fileEnote = $_FILES['eNote']['name'];
$path1 = $file.$pic1.'.'.$ext1;
$path2 = $file.$pic2.'.'.$ext2;
$path3 = $file.$pic3.'.'.$ext3;
print_r($path1);
$ory1 = $sfish.$pic1.'.'.$ext1;
$ory2 = $sfish.$pic2.'.'.$ext2;
$ory3 = $sfish.$pic3.'.'.$ext3;
if (!file_exists($path1))
{
move_uploaded_file ($_FILES['pic1']['tmp_name'], $path1) or die ("Error");
}
if (!file_exists($path2))
{
move_uploaded_file ($_FILES['pic2']['tmp_name'], $path2) or die ("Error");
}
if (!file_exists($path3))
{
move_uploaded_file ($_FILES['pic3']['tmp_name'], $path3) or die ("Error");
}
if(!empty($pic1)) {
$sql5= "INSERT INTO pimage (id, proid, image)
VALUES ('', $lastid, '$ory1')";
mysql_query($sql5) or die ("Error in query: $sql5");
}
else
{
$not = "not good";
print_r($not);
}
if(!empty($pic2)) {
$sql5= "INSERT INTO image (resID, image)
VALUES ($lastid, '$ory2')";
mysql_query($sql5) or die ("Error in query: $sql5");
}
else
{
$not = "not good";
print_r($not);
}
if(!empty($pic3)) {
$sql5= "INSERT INTO image (resID, image)
VALUES ($lastid, '$ory3')";
mysql_query($sql5) or die ("Error in query: $sql5");
}
else
{
$not = "not good";
print_r($not);
}
?>
print_r($pic1) are not outputting anything. print_r($path1) just outputting slider_imagesClient/50/.
How can I solve this? I'm suspecting error in the form but I couldn't find any. Thank you very much :D. Really appreciate your help.
echo '<table width="70%">';
echo '<tr>';
echo '<td>Add Promotion</td>';
echo '</tr>';
echo "<form action='addpromotion_post.php' method='post'
enctype='multipart/form-data' name='form1' id='form1'>";
change like this
echo "<form action='addpromotion_post.php' method='post' enctype='multipart/form-data' name='form1' id='form1'>";
echo '<table width="70%">';
echo '<tr>';
echo '<td>Add Promotion</td>';
echo '</tr>';