I am trying to fetch my database results but it's not displaying any content.
Please help me to find the error:
<?
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
// Search from MySQL database table
$search=$_POST['search'];
$query = $pdo->prepare("select * from usermark where sid LIKE '%$search%' LIMIT 0 , 1");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0) {
echo "<tr><td colspan='2' bgcolor='#800000'><p align='center'><font face='Verdana' color='#FFFFFF'>RESULTS</font></td></tr>";
echo "<tr><td width='29%'></td><td width='69%'></td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td width='29%'>NAME</td><td width='69%'></td></tr>";
echo "<tr><td width='29%'>ID</td><td width='69%'>";
echo $results['sid'];
echo "</td></tr><tr><td width='29%'>ROLL NO.</td><td width='69%'></td></tr>";
echo "<tr><td width='29%'>OMR NO.</td><td width='69%'>";
echo $results['somr'];
echo "</td></tr><tr><td width="29%"></td><td width="69%"></td></tr>";
echo "<tr><td width="29%">TOTAL MARKS</td><td width="69%">";
echo $results['smark'];
echo "</td></tr><tr><td width='29%'>MARKS OBTAINED</td><td width='69%'></td></tr>";
echo "<tr><td width='29%'>PERCENTAGE</td><td width='69%'></td></tr>";
echo "</table>";
} else {
echo 'Nothing found';
}
}
?>
You're binding to a variable incorrectly, in your sql string and in bindValue().
Change:
$query = $pdo->prepare("select * from usermark where sid LIKE '%$search%' LIMIT 0 , 1");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
With:
$query = $pdo->prepare("select * from usermark where sid LIKE '%:search%' LIMIT 0 , 1");
$query->bindValue(":search", $search, PDO::PARAM_STR);
You also have a bad conditional statement.
Also Change:
if (!$query->rowCount() == 0) {
To:
if ($query->rowCount() != 0) {
Related
I have a PHP search form for searching in a SQL table.
All together it works great, but there is one thing I like to change.
The whole table is visible on the screen BEFORE the search.
I would like to mention only the records after a search.
Does anybody know to hide the table in PHP?
Many thanks in advance!
HTML
<form action="" method="post">
<input type="text" name="search" placeholder="Search">
<input type="submit" value="Submit" />
</form>
PHP
<?php
$host = "******";
$user = "******";
$password = "******";
$database_name = "vangsten";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
$search=$_POST['search'];
$query = $pdo->prepare("select * FROM meldingen WHERE soort LIKE '%$search%' OR zone LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0) {
echo "<table style=\"margin:50px auto;\">";
echo "<tr><td>VISSOORT</td><td>LENGTE</td><td>AANTAL</td><td>ZONE</td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td>";
echo $results['soort'];
echo "</td><td>";
echo $results['lengte'];
echo "</td><td>";
echo $results['aantal'];
echo "</td><td>";
echo $results['zone'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
?>
This is because even when there is no search passed you will end up running the query: with WHERE sort LIKE '%%'
You should check if a search has been passed first
if(array_key_exists('search',$_POST) && !empty($_POST['search'])){
$search=$_POST['search'];
$query = $pdo->prepare("select * FROM meldingen WHERE soort LIKE '%$search%' OR zone LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0) {
echo "<table style=\"margin:50px auto;\">";
echo "<tr><td>VISSOORT</td><td>LENGTE</td><td>AANTAL</td><td>ZONE</td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td>";
echo $results['soort'];
echo "</td><td>";
echo $results['lengte'];
echo "</td><td>";
echo $results['aantal'];
echo "</td><td>";
echo $results['zone'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
}
array_key_exists('search',$_POST) checks that there is a value with
the key 'search;'
!empty($_POST['search']) checks it is not just
an empty string. (You may want to allow this)
You could use isset($_POST['search']) instead of array_key_exists('search',$_POST) but array_key_exists is better practice as isset still returns false if the value is NULL
You can check if the user has clicked on the search button:
if (isset($_POST['search'])) {
// do your table generation here
}
I got problem that, my Pagination first pages sortby Id,name,code or whatever I want. But next pages automatic short by id, not option I want. Don't understand how to make this work. Tried diffirent things, but same result.
This is how my code looks:
public function selectParts()
{
try
{
$stmt = $this->conn->prepare("SELECT count(*) FROM partcatalogue");
$stmt->execute();
$total = $stmt->fetchColumn();
$perpage = 10;
$pages = ceil($total / $perpage);
$get_pages = isset($_GET['page']) ? $_GET['page'] : 1;
$data = array(
'options' => array(
'default' => 1,
'min_range' => 1,
'max_range' => $pages
)
);
$number = trim($get_pages);
$number = filter_var($number, FILTER_VALIDATE_INT, $data);
$range = $perpage * ($number - 1);
$prev = $number - 1;
$next = $number + 1;
$stmt = $this->conn->prepare("SELECT part_id,image,name,manufacture,category,code FROM partcatalogue ORDER BY part_id LIMIT :limit, :perpage");
$stmt->bindParam(':perpage', $perpage, PDO::PARAM_INT);
$stmt->bindParam(':limit', $range, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
if((isset($_GET['action']) ? $_GET['action'] : null) == "sortbyId")
{
$stmt = $this->conn->prepare("SELECT part_id,image,name,manufacture,category,code FROM partcatalogue ORDER BY part_id ASC LIMIT :limit, :perpage");
$stmt->bindParam(':perpage', $perpage, PDO::PARAM_INT);
$stmt->bindParam(':limit', $range, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
}
if((isset($_GET['action']) ? $_GET['action'] : null) == "sortbyName")
{
$stmt = $this->conn->prepare("SELECT part_id,image,name,manufacture,category,code FROM partcatalogue ORDER BY name ASC LIMIT :limit, :perpage");
$stmt->bindParam(':perpage', $perpage, PDO::PARAM_INT);
$stmt->bindParam(':limit', $range, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
}
if((isset($_GET['action']) ? $_GET['action'] : null) == "sortbyCode")
{
$stmt = $this->conn->prepare("SELECT part_id,image,name,manufacture,category,code FROM partcatalogue ORDER BY code ASC LIMIT :limit, :perpage");
$stmt->bindParam(':perpage', $perpage, PDO::PARAM_INT);
$stmt->bindParam(':limit', $range, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
}
if((isset($_GET['action']) ? $_GET['action'] : null) == "sortbyManufacture")
{
$stmt = $this->conn->prepare("SELECT part_id,image,name,manufacture,category,code FROM partcatalogue ORDER BY manufacture ASC LIMIT :limit, :perpage");
$stmt->bindParam(':perpage', $perpage, PDO::PARAM_INT);
$stmt->bindParam(':limit', $range, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();$stmt->execute();
}
if((isset($_GET['action']) ? $_GET['action'] : null) == "sortbyCategory")
{
$stmt = $this->conn->prepare("SELECT part_id,image,name,manufacture,category,code FROM partcatalogue ORDER BY category ASC LIMIT :limit, :perpage");
$stmt->bindParam(':perpage', $perpage, PDO::PARAM_INT);
$stmt->bindParam(':limit', $range, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
}
echo "<table style='width:100%'>";
echo "<tr>";
echo "<th>"; ?>Id</th><?php
echo "<th>"; ?>Image</th><?php
echo "<th>"; ?>Name</th><?php
echo "<th>"; ?>Code</th><?php
echo "<th>"; ?>Manufacture</th><?php
echo "<th>"; ?>Category</th><?php
echo "<th>"; ?>Edit<?php
echo "<th>"; ?>Delete<?php
echo "</tr>";
foreach($result as $part){
echo "<td>"; echo $part['part_id']; echo "</td>";
echo "<td>"; echo "<img src='../../Images/Part/".$part['image']."' width='50' height='50'/>"; echo"</td>";
echo "<td>"; echo $part['name']; echo "</td>";
echo "<td>"; echo $part['code']; echo "</td>";
echo "<td>"; echo $part['manufacture']; echo "</td>";
echo "<td>"; echo $part['category']; echo "</td>";
echo "<td>"; ?>Edit<?php echo"</td>";
echo "<td>"; ?>Delete<?php echo"</td>";
echo "</hr>";
echo "</tr>";
echo "</hr>";
}
echo "</table>";
if($result && count($result) > 0)
{
echo "<h4>Total pages ($pages)</h4>";
# first page
if($number <= 1)
echo "<span>« prev</span> | next »";
# last page
elseif($number >= $pages)
echo "« prev | <span>next »</span>";
# in range
else
echo "« prev | next »";
}
else
{
echo "<p>No results found.</p>";
}
return $result;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
How do I to display the latest booking result where $date > strtotime("now"), as I can only display the booking records.
This is my PHP code
$mysqli = new mysqli("", "", "", "");
$stmt = $mysqli->prepare("SELECT bookingid, date, slot, location FROM booking WHERE username=?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($bookingid, $date, $slot, $location);
echo"<table>";
echo"<b>Latest Bookings</b>";
echo "<tr><th><b>Date</b></th>
<th><b>Slot</b></th>
<th><b>Location</b></th>
<th><b>Actions</b></th>";
while ($stmt->fetch()) {
if( $date > strtotime("now")) {
echo "<tr>";
echo "<td><p>$date";
echo "<td><p>$slot</td>";
echo "<td><p>$location</td>";
echo "</tr>";
echo "</table>";
}
else{
echo"<table>";
echo"<b>Booking History</b>";
echo "<tr><th><b>Date</b></th>
<th><b>Slot</b></th>
<th><b>Location</b></th>";
while ($stmt->fetch()) {
echo "<tr>";
echo "<td><p>$date";
echo "<td><p>$slot</td>";
echo "<td><p>$location</td>";
echo "</tr>";
echo "</table>";
}
}
}
Change $date > strtotime("now") to this strtotime($date) > strtotime("now"), I hope it will work
I'm inserting some values into my database, which is working successfully. However when i insert a new value for an id that has a previous value, the old val isn't replaced by the new, instead they're kept both. I'm trying to update the function with an if/else statement (commented part). But still the same result.
$options = '';
$filter=mysql_query("select afnumber from employees WHERE Status='Employed '");
while($row = mysql_fetch_array($filter)) {
$options .="<option >" . $row['afnumber'] . "</option>";
}
$menu="<form id='filter' name='filter' method='post' action=''>
AFNumber : <select name='SelectAF' id='filter' style='color:grey;'>" . $options . "</select>
Added hours: <input type='text' name='AddedHours' style=' padding: 10px;border: solid 2px #c9c9c9; width:50px; height:2px;'>
<input type='submit' name='submit' value='Submit' style='width:80px; height:30px; text-align:center; padding:0px;'>
</form>
<br>
";
/* if(isset($_POST['submit'])){
$addedhours = $_POST['AddedHours'];
$selectaf = $_POST['SelectAF'];
if($addedhours == ""){
$sql="INSERT INTO `editedworkhours` (`AFNumber`,`AddedWH`) VALUES('$selectaf','$addedhours')";
$getResult =mysql_query($sql);
}
else{
$sql2 = "UPDATE editedworkhours SET AddedWH=$addedhours WHERE AFNumber=$selectaf";
$getResult =mysql_query($sql2);
}
}
echo $menu; */
echo '<div class="scrolldiv">';
try {
$conn = new PDO('mysql:host=localhost;dbname=hr', 'root', 'J546');
$conn->exec("set names utf8");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$num_rows = $conn->query('SELECT COUNT(*) FROM employees')->fetchColumn();
$pages = new Paginator($num_rows,9,array(15,3,6,9,12,25,50,100,250,'All'));
echo $pages->display_pages();
echo "<span class=\"\">".$pages->display_jump_menu().$pages->display_items_per_page()."</span>";
$stmt = $conn->prepare("SELECT employees.afnumber,employees.name,employees.dateofemployment,employees.actualpost,employees.department FROM employees WHERE employees.status='Employed' AND (employees.afnumber LIKE '%$search%' OR employees.name LIKE '%$search%') ORDER BY employees.afnumber DESC LIMIT :start,:end");
$stmt->bindParam(':start', $pages->limit_start, PDO::PARAM_INT);
$stmt->bindParam(':end', $pages->limit_end, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
$ewhtable = "<table class='sortable'><tr><th>AFNumber</th><th>Employee Name</th><th>Years of Service</th><th>Actual Post</th><th>Department</th><th>Added Hours</th></tr>\n";
foreach($result as $row) {
$years=explode("/", $row[2]);
$years[2]=intval(date ('Y')) - $years[2];
$sql="SELECT addedwh FROM editedworkhours WHERE afnumber='$row[0]'";
$var = "";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result2 = $stmt->fetchAll();
foreach ($result2 AS $row2) {
$var .= $row2['addedwh'] . "\n";
}
$ewhtable .= "<tr><td>$row[0]</td><td>$row[1]</td><td>$years[2]</td><td>$row[3]</td><td>$row[4]</td><td>$var</td></tr>\n";
}
$ewhtable .= "</table>\n";
echo $ewhtable;
exportTable(str_replace("&","",$ewhtable),"EmployeeWorkingHoursTable");
echo $pages->display_pages();
echo "<p class=\"paginate\">Page: $pages->current_page of $pages->num_pages</p>\n";
echo "</div>";
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
If AddedHours input value has only a space, your comparison if($addedhours == "") will fail.
Always trim the values before comparison.
$addedhours = trim($_POST['AddedHours']);
I have the following two prepared statements. The db connection and queries are correct, I have tested them within phpmyadmin. I also tested inside of my while fetch loop to see if I am pulling the data I am supposed to be and I am.
The problem resides in my while and foreach loops or possibly my num rows statement. I am not sure what I am doing incorrectly in there.
I am getting this error:
Warning: mysqli::query() expects parameter 1 to be string, object given
For this while loop:
while ($row2 = $result->fetch_assoc() ) {
I am also getting my else statement..
echo "<p>This topic does not exist.</p>";
Even though the info is echoing out correctly, again I just think my loops are wrong?
Does anyone see what I am doing wrong in my loops?
$con = new mysqli("localhost", "", "", "");
if (mysqli_connect_errno()) {
throw new Exception("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* activate reporting */
$driver = new mysqli_driver();
try {
$cid = $_GET['cid'];
$tid = $_GET['tid'];
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
echo $cid . "<br>";
echo $tid;
//Prepare
if ($stmt = $con->prepare("SELECT * FROM forum_topics WHERE `category_id`=? AND `id`=? LIMIT 1")) {
$stmt->bind_param("ii", $cid, $tid);
$stmt->execute();
$stmt->bind_result($topic_id, $category_id, $topic_title, $topic_creator, $topic_last_user, $topic_date, $topic_reply_date, $topic_views);
if (!$stmt) {
throw new Exception($con->error);
}
}
while ($row = $stmt->fetch()) {
$stmt->store_result();
$numrows = $stmt->num_rows;
echo $numrows;
}
if($numrows == 1){
echo "<table width='100%'>";
if ( $_SESSION['user'] ) {
echo "<tr><td colspan='2'><input type='submit' value='Add Reply' onclick=\"window.location =
'forum_post_reply.php?cid=".$cid."$tid=".$tid."'\"> <hr />";
} else {
echo "<tr><td colspan='2'><p>Please log in to add your reply</p><hr /></td></tr>";
}
}
foreach($stmt as $row) {
//Prepared SELECT stmt to get forum posts
if($stmt2 = $con->prepare("SELECT `id`, `category_id`, `topic_id`, `post_creator`, `post_content`, `post_date` FROM forum_posts WHERE `category_id`=? AND `topic_id`=?")) {
$stmt2->bind_param("ii", $cid, $tid);
$stmt2->execute();
$stmt2->bind_result($post_id, $post_category_id, $post_topic_id, $post_creator, $post_content, $post_date);
if (!$stmt2) {
throw new Exception($con->error);
}
}
}
if ($result = $con->query($stmt)) {
while ($row2 = $result->fetch_assoc() ) {
echo "<tr><td valign='top' style='border: 1px solid #000000;'>
<div style='min-height: 125px;'>".$row['topic_title']."<br />
by ".$row2['post_creator']." - " .$row2['post_date']. "<hr />" . $row2['post_content'] ."</div></td>
<td width='200' valign='top' align='center' style='border: 1px solid #000000;'>User Info Here!</td></tr>
<tr><td colspan='2'><hr /></td></tr>";
}
} else {
echo "<p>This topic does not exist.</p>";
}
}
catch (Exception $e)
{
echo "Error: " . $e->getMessage();
}
if you search on $stmt with ctrl-F in your browser (and ignoring $stmt2), you will notice that $stmt is a prepared statement all the way down to the error line. $stmt comes to life as a return type from prepare, is bound, and executed.
later on you:
if ($result = $con->query($stmt)) {
so $con->query() is expecting a string, not an object, no?
From the manual.
Not that there aren't other things to consider under a microscope, but I hope this narrowly answers the error message for you.
Edit:
Apparently, you cannot use bind_result with select *. Read the gents Accepted Answer to this question. He does 2 examples, 1 with 1 without select *. Also note store_result()
Here is the link to his answer that was upvoted quite a bit.