I have a program, that searches a database from a PHP file, linking back to the some file with the output.
It works perfectly in all browsers, excluding IE. I have no idea why.
Here is my code:
<?php
if( isset( $_POST['schoolname'] ) && strlen( trim( $_POST['schoolname'] ) ) > 0 )
{
$school = filter_input(INPUT_POST, 'find', FILTER_SANITIZE_STRING);
$school = $_POST['schoolname'];
#connecting to the database
$conn = mysql_connect("localhost", "root");
mysql_select_db("finalproject");
$sql = "select * from presentations where school like '%$school%'";
$result = mysql_query($sql, $conn) or die(mysql_error());
#this is the array that stores and displays the results of the search
if ( mysql_num_rows($result) >0)
{
while ($newArray = mysql_fetch_array($result))
{
$school = $newArray['school'];
$date = $newArray['date'];
$place = $newArray['place'];
$time = $newArray['time'];
echo $school . ", " . $place . ", " . $date . ", " . $time . "<br />" . "<br />";
}
}
else
{
echo "Record not found" . "<br />" . "<br />";
}
mysql_close($conn);
}
?>
<!-- The form in which the search happens -->
<form action=" " method="post">
School's name: <input type="text" name="schoolname">
<input type="submit" name="button" value="Search">
</form>
This is just my code for within the IFrame.
Related
I'm trying to create a search bar for my website on my local server, but when I submit the page generated is just blank. I've been following a couple of guides online but can't seem to figure out why it is not connecting to my MySQL db and getting the results. This is my first time attempting db and PHP so appreciate all advice.
<form action="./search.php" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
Search.php
<?php
$conn = mysqli_connect("localhost", "root", "root", "womendig_search");
if(mysqli_connect_errno()){
echo "Failed to connect: " . mysqli_connect_error();
}
error_reporting(0);
$output = '';
if(isset($_GET['q']) && $_GET['q'] !== ' '){
$searchq = $_GET['q'];
$q = mysqli_query($conn, "SELECT * FROM search WHERE keywords LIKE '%$searchq%' OR title LIKE '%$searchq%'") or die(mysqli_error());
$c = mysqli_num_rows($q);
if($c == 0){
$output = 'No search results for <b>"' . $searchq . '"</b>';
} else {
while($row = mysqli_fetch_array($q)){
$id = $row['id'];
$city = $row['city'];
$country = $row['country'];
$descriptions = $row['descriptions'];
$output .= '<h3>' . $title . '</h3>
<p>' . $desc . '</p>
';
}
}
} else {
header("location: ./");
}
print("$output");
mysqli_close($conn);
?>
The $title and $desc were not defined so you have empty <h3> and empty <p> tags.
Also i think it's better to make a few changes in your code.
Use !empty($_GET['q']) instead of $_GET['q'] !== ' ' and use extract($row); instead of
$id = $row['id'];
$city = $row['city'];
$country = $row['country'];
$descriptions = $row['descriptions'];
I have a form which updates information inside of a DB, everything works perfectly as it should....... except for some reason the header does not work for me. I am using the header redirect in a lot of other scripts within the same site; it is just this one script that the header redirect does not work. I know that the if statement the header is inside of is called because the echo right below the header is displayed on the page, its just kind of ignoring the header line. If you have any suggestions that would be very helpful.
The code below has been minimized so its not to long for everyone to read but if it is still a problem ill clean it up even more
the form
<form class="editUser" action="uploadEmployee.php" method="post" enctype="multipart/form-data" />
<input name="editUserFirstName" id="editUserFirstName" type="text" placeholder="Enter The User's First Name" />
<label>Employee's Coverage</label>
<input type="file" name="file_array[]" placeholder="Add The Employees Coverage" />
<input name="addUserSubmit" type="submit" value="Submit" />
</form>
The uploading scripts
<?php
include("includes/connect.inc.php");
if(isset($_FILES['file_array'])){
$day = date('d');
$month = date('m');
$dateObj = DateTime::createFromFormat('!m', $month);
$monthName = $dateObj->format('F'); // March
$year = date('Y');
$date = $monthName . ", " . $day . ", " . $year;
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
$payCheque = $name_array[0];
$T4 = $name_array[1];
$coverage = $name_array[2];
$selectedId = $_POST['editId'];
$name = $_POST['editUserFirstName'];
if($_POST['editUserPermission']){
$permission = "1";
}else{
$permission = "0";
}
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
$title = "This Is A Test Title";
$icon = "0";
if($i == 0){
$icon = "1";
$title = "You Have Received A New Pay Cheque";
$comment = "Hello " . $name . ", click view document to view and download your pay cheque for " . $date . ". Your pay cheque will be a PDF file. Thank you.";
}
$sql = "INSERT INTO securedFiles (title, date, PDF, comment, idOfUser, icon)
VALUES ('$title', '$date', '$name_array[$i]', '$comment', '$documentId', '$icon')";
if ($connect->query($sql) === TRUE) {
//header("Location: hub.php");
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
echo $payCheque ." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
$sql = "UPDATE dealerEmployees SET firstName = '$_POST[editUserFirstName]', lastName = '$_POST[editUserLastName]', password = '$_POST[editUserPW]', permission = '$permission', address = '$_POST[editUserAddress]', email = '$_POST[editUserEmail]', phone = '$_POST[editUserPhone]' WHERE id = $selectedId";
if ($connect->query($sql) === TRUE) {
header('Location: hub.php');
echo "Success";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
}
//$connect->close();
?>
header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
And in your case, you are using echo before header()
So you can use a redirect method(that i use in all my projects, no problems ever)
<?php
if ($connect->query($sql) === TRUE) {
echo "<script> parent.self.location = \"hub.php\";</script>";
echo "Success";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
?>
I am creating a time clock application. I have set it up so each user has their own table and it would select that table and all the rows in that table. I want to figure out how to get the difference between the in and next out punch. I am assuming that each in punch will correspond with the next out punch (the next row in the table (when ordering by ID)) I can only think of datediff. I know that is the case, but I have no clue how to implement. I am a very new php developer (Just this past week!) I have no clue how to calculate the difference between each in and out. I have looked at this question: calculate the difference of the time between In and out but couldn't figure it out there or here: mysql timeclock. Any help is appreciated.
My exact question is how to get the difference between each in and out punch in a table.
FILE:
<head>
<title>View My Punches</title>
<body bgcolor="#9966FF">
<link rel="icon" type="image/ico" href="http://example.com/time/favicon.ico"/>
</head>
<?php
error_reporting(E_ALL); ini_set('display_errors', 0);
define('DB_NAME', 'name');
define('DB_USER', 'user');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'host');
$link = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($link->connect_errno > 0){
die('Could not connect: ' .connect_error());
}
$userid_value = $_POST['userid'];
$table = "tc_".$userid_value;
$checkusersql = "SELECT * FROM tc_users WHERE userid = '$userid_value'";
$usercheck = $link->query($checkusersql);
$punchessql = "SELECT * FROM $table ORDER BY id";
$result = $link->query($punchessql);
$unixtime = time() + 60*60;
$time_value = date("h:i:s A", $unixtime);
$date_value = date("m/d/Y", $unixtime);
if ($usercheck->num_rows == 0) {
echo "Sorry, " . $userid_value . " is not a valid user ID. Please try again.";
}else {
echo "Punch Report for " . $userid_value . " | Generated at " . $time_value . " on " . $date_value;
echo "<p></p>";
if ($result->num_rows == 0) {
echo "<p></p>";
echo "No punches were found for " . $userid_value . ".";
}else{
echo "<table border=1>";
echo "<tr><th>Punch ID</th><th>Time</th><th>Punch Type</th><th>Group</th><th>Department</th><th>Notes</th></tr>";
while ($row = $result->fetch_array())
{
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['time'] . "</td><td>" . $row['punchtype'] . "</td><td>" . $row['groupname'] . "</td><td>" . $row['dept'] . "</td><td>" . $row['notes'] . "</td>";
}
echo "</table>";
}
}
$differs = array();
$inout = array();
$current = array('in'=>array(),'out'=>array(),'length'=>'');
foreach ( $row as $each)
{
if ( $each['punchtype'] == 'in' )
{
if ( empty($current['in']) )
{ $current['in'] = $each; }
}
else if ( $each['punchtype'] == 'out' )
{
if ( empty($current['out']) )
{ $current['out'] = $each; }
}
if (( !empty($current['in']) && !empty($current['out'])))
{
$in = new DateTime($current['in']);
$out = new DateTime($current['out']);
$current['length'] = $in->diff($out);
$inout[] = $current;
$stamp = $inout['length'];
$stampformat = $stamp->format('%s');
$stampint = intval($stampformat);
$stampintval = $stampint/3600;
echo $stampintval;
#array_push($differs, );
}
}
?>
 
 
<form method="GET" action="http://example.com/time/panel.php">
<input type="submit" value="Go Home">
</form>
It will be much simpler to do this in PHP instead of in the database. Let's assume that you've pulled all the records into a variable, $allofit, and that the records are already sorted by your datetime field. Now you need to pair them up into in-out sets.
$inout = array();
$current = array('in'=>array(),'out'=>array(),'length'=>'');
foreach ( $allofit as $each)
{
if ( $each['punchtype'] == 'in' )
{
if ( empty($current['in']) )
{ $current['in'] = $each; }
}
else if ( $each['punchtype'] == 'out' )
{
if ( empty($current['out']) )
{ $current['out'] = $each; }
}
if ( !empty($current['in']) && !empty($current['out'])
{
$in = new DateTime($current['in']);
$out = new DateTime($current['out']);
$current['length'] = $in->diff($out);
$inout[] = $current;
}
}
Note that your current schema can have mis-matched in-out sets. (in # 1:14, in # 1:15, out # 1:40) This code will silently drop the mismatches; you should probably do what you can to make sure mismatches don't happen in the first place.
The database table only contains the four fields that the query is attempting to insert into. For some reason I get the error: Query failed: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined.
I have troubleshot by echoing the output of the foreach loops and it always returns four items, I'm not sure what parameter isn't defined. I have also played around with including the field names in the $sql string as well as not including them. Same results either way. Please help if you can.
<?php
class DB {
private $_conn;
public function openDB() {
$dsn = "mysql:host=localhost;dbname=news";
$username = "root";
$password = "password";
try {
$this->_conn = new PDO( $dsn, $username, $password );
$this->_conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
echo "Connection failed: " . $e->getMessage();
}
}
public function closeDB() {
$this->_conn = null;
}
public function selectData( $myQuery ) {
$rows = $this->_conn->query( $myQuery );
foreach ( $rows as $row ) {
echo "Index: " . $row['id'] . "<br />";
echo "Title: " . $row['title'] . "<br />";
}
}
public function insertData( $tableName ) {
$q = $this->_conn->prepare("DESCRIBE " . $tableName);
$q->execute();
$getFields = $q->fetchAll(PDO::FETCH_COLUMN);
$dbFieldCount = count( $getFields );
$implodedFields = implode( ", :", $getFields );
//$sql = "INSERT INTO " . $tableName . " ( " . implode( ", ", $getFields ) . " ) VALUES ( :" . $implodedFields . " )";
$sql = "INSERT INTO " . $tableName . " VALUES ( :" . $implodedFields . " )";
echo "$sql<br />";
try {
$insert = $this->_conn->prepare( $sql );
foreach ( $getFields as $dbKey => $dbValue ) {
foreach( $_POST as $formKey => $formValue ) {
if ( $dbValue == 'id' ) {
$insert->bindValue( '\":' . $dbValue . '\"', null, PDO::PARAM_INT );
echo "$dbValue<br />";
break;
} else if ( is_int( $formValue ) && $dbValue == $formKey ) {
$insert->bindValue( '\":' . $dbValue . '\"', $formValue, PDO::PARAM_INT );
echo "$formValue<br />";
break;
} else if ( is_string( $formValue ) && $dbValue == $formKey ) {
$insert->bindValue( '\":' . $dbValue . '\"', $formValue, PDO::PARAM_STR );
echo "$formValue<br />";
break;
}
}
}
$insert->execute();
} catch ( PDOException $e ) {
echo "Query failed: " . $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
if ($_POST) {
$conn = new DB();
$conn->openDB();
$conn->insertData( 'login' );
$conn->closeDB();
}
?>
<form action="#" method="POST" name="register">
<label for="username">Username</label><br />
<input type="text" id="username" name="username"><br />
<label for="password">Password</label><br />
<input type="password" id="password" name="password"><br />
<label for="email">Email Address</label><br />
<input type="text" id="email" name="email"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
$sql = "INSERT INTO " . $tableName . " VALUES ( :" . $implodedFields . " )";
Here you're adding all columns into your SQL statement, but later you only add values that are sent when the form is submitted. It's possible that you have columns in your database that aren't in the form, so you're coming up with a statement like:
INSERT INTO someTable VALUES (:id, :value1, :value2)
And then you only bind :id and :value1, leaving MySQL confused about what :value2 is supposed to be.
I have a while loop printing multiple checkboxes..I changed them to checkboxes instead of radio buttons.. now all I want to do is pass the names of all those checkboxes to my vote.php file. If I give my checkbox in my loop a simple name and carry that over to my vote.php which handles all my POST data, it only carries over my last selection.. I want all of my selections. I cleaned my code up for you guys a little bit.
Tell me where I am going wrong here.. here is my initial code printing the buttons..
while($row_nominee=mysql_fetch_array($result_nominee)){
$id = $row_nominee[0];
//print "$level";
$prefix = $row_nominee[1];
$fname = $row_nominee[2];
$lname = $row_nominee[3];
$suffix = $row_nominee[4];
$city = $row_nominee[5];
$state = $row_nominee[6];
$zip = $row_nominee[7];
$bio = $row_nominee[8];
$level = $row_nominee[10];
$name = $prefix . " " . $fname . " " . $lname;
$address = $city . " " . $state . " " . $zip;
//print "$voted";
print "<tr>";
print "<td width=\"4\" valign=\"top\"><input type=\"checkbox\" name=\"candidateOne\" id=\"candidate\" value=$id></td>";
print "<td valign=\"top\"><FONT face=Tahoma,Arial,Helv size=-1><b>Name:</b> <font color=\"#ff0000\">$name</font><br><b>Hometown:</b> $address<br><b>Bio:<br /></b> $bio</font></td>";
print "</tr>";
}
?>
//now here is my vote.php file which handles the checkboxes.
//get the contents from the vote ballot Form
$voter_id = safeEscapeString(qsrequest(voter));
$candidate_id = safeEscapeString(qsrequest(candidateOne));
//print "$voter_id and $candidate_id";
include '../../sql/usagym_connection.php';
if(qsrequest(correct))
{
$voter_id1= safeEscapeString(qsrequest(voter1));
$candidate_id1= safeEscapeString(qsrequest(candidate1));
$votes1= safeEscapeString(qsrequest(votes1));
$votes1 += 1;
$sql_voter = "update stateChair_voters set voted='Y' where (usagnum='$voter_id1')";
//print "$sql_voter<br>";
$result_voter = mysql_query($sql_voter, $link) or die("Invalid query2");
$update_candidate = "update stateChair_nominees set votes=$votes1 where (id=$candidate_id1)";
//print "$update_candidate<br>";
$result_update = mysql_query($update_candidate, $link) or die("Invalid query3");
//print "Total votes is $votes1.";
header( "Location: vote_thanks.html");
exit;
}
else
{
//connect the database
$sql_candidate = "select id, prefix, fname, lname, suffix, city, state, zip, bio, votes from stateChair_nominees where id=$candidate_id";
$result_candidate = mysql_query($sql_candidate, $link) or die("Invalid query1". mysql_error());
while($row_candidate=mysql_fetch_array($result_candidate)){
$id = $row_candidate[0];
$prefix = $row_candidate[1];
$fname = $row_candidate[2];
$lname = $row_candidate[3];
$suffix = $row_candidate[4];
$city = $row_candidate[5];
$state = $row_candidate[6];
$zip = $row_candidate[7];
$bio = $row_candidate[8];
$votes = $row_candidate[9];
$name = $prefix . " " . $fname . " " . $lname;
$address = $city . " " . $state . " " . $zip;
}
?>
All I really want to do is submit multiple people to a vote and not just one person. Thoughts? Thanks guys!
Here is my code for my checkboxes..
print "<td width=\"4\" valign=\"top\"><input type=\"checkbox\" name=\"candidateOne\" id=\"candidate\" value=$id></td>";
Now here is the code that handles these checkboxes.. I didn't write this code and I am having to debug it, so any help is appreciated.
$candidate_id = safeEscapeString(qsrequest(candidateOne));
This code right now handles a string, not a variable. What's the process in having a variable represent multiple checkboxes on the other file while recording them on here?
print "<td width=\"4\" valign=\"top\"><input type=\"radio\" name=\"candidateOne\" id=\"candidate\" value=$id></td>";
You must change the 'name' as you have changed the 'value' in the loop by a variable.