I have this code and in "SELECT * FROM Blogi WHERE PostID=".
How to get each line separately so that takes postedBY, title, date, content by PostID
<?php
try{
$Blog = $conn->prepare("SELECT * FROM Blogi WHERE PostID=");
$Blog->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
$fetch = $Blog->fetchAll();
$usercount = $Blog->rowCount();
if($usercount > 0){
foreach($fetch as $f){
$PostID = $f['PostID'];
$PostedBY = $f['PostedBY'];
$Title = $f['Title'];
$Date = $f['Date'];
$Content = $f['Content'];
}
}else{
session_destroy();
header('location: index.php');
}
?>
I have very bad English, so I don't know anyone can understand this.
How to do it further this postID="" to that he would start to work?
You have already done it in foreach loop... so add a line for output like... Also you aren't sending any PostID value to your query, be sure that you are sending a value for it.
foreach($fetch as $f){
$PostID = $f['PostID'];
$PostedBY = $f['PostedBY']
$Title = $f['Title'];
$Date = $f['Date'];
$Content = $f['Content'];
echo $PostID . " " . $Title . " " . $Date . " " . $Content . "<br />";
}
I am creating a multiuser shared to do list application using PHP and MySQL. Currently, my application is displaying the to do list items by iterating over the database table with a while loop.
All of that works correctly, so I know I am connecting to the database. Part of the while loop also generates buttons that allow a user to "claim" an item that does not have anyone working on it or to indicate that at item has been completed. However, the buttons are not updating the database table.
<?php
include 'includes/dbh.inc.php';
$sql = 'SELECT * FROM items WHERE item_is_done = 0';
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$creator = $row['item_creator'];
$owner = $row['item_owner'];
$id = $row['item_id'];
if (isset($_POST['do_item'])) {
$update = "UPDATE items SET item_owner = $currentID WHERE item_id = $id;";
mysqli_query($conn, $update);
header("Location: ../todo.php?code=doing");
exit();
} else if(isset($_POST['complete_item'])) {
$update = "UPDATE items SET item_is_done = 1 WHERE item_id = $id;";
mysqli_query($conn, $update);
header("Location: ../todo.php?code=done");
exit();
}
echo '<h4>Item ID:</h4>' . $id . '<br><br>';
echo '<h4>Item created by:</h4>' . $creator . '<br><br>';
echo '<h4>Date Added: </h4>' . $row['item_add_date'] . '<br><br>';
echo '<h4>Item Title: </h4>' . $row['item_title'] . '<br><br>';
echo '<h4>Description: </h4>' . $row['item_description'] . '<br>';
if($row['item_owner'] == 'None') {
echo '<br>';
echo '<button type="submit" name="do_item" formaction="todo.php" formmethod="POST">Do Item</button>';
echo '<br>';
} else if($row['item_owner'] != 'None') {
echo '<br>';
echo '<h4>Item is being worked on by: </h4>' . $owner . '<br><br>';
echo '<button type="submit" name="complete_item" formaction="todo.php" formmethod="POST">Complete Item</button>';
echo '<br>';
}
echo '<hr>';
}
?>
I was also got stuck on same kind of problem what I did was I tried to put the updating variables in ' ' single quotes.
If it can help you you can try this queries
$update = "UPDATE items SET item_owner='$currentID' WHERE item_id='$id'";
$update = "UPDATE items SET item_is_done='1' WHERE item_id ='$id'";
I was wondering if somebody could help shed some light as to why this PHP code is not entering into the for loop? In MySQL the query returns the appropriate rows that I need but in this PHP file it fails to return anything into the array, thus not executing the foreach loop.
CODE
<?php
try {
$sql = 'SELECT FirstName,LastName ';
$sql .= 'FROM adventureworks.employeedepartmenthistory ';
$sql .= 'JOIN employee USING(EmployeeID) ';
$sql .= 'JOIN contact USING(ContactID) ';
$sql .= 'WHERE DepartmentID = 2';
$stmt = $dbh->prepare($sql);
$stmt->execute();
echo $sql;
echo '<ul>';
foreach ($stmt->fetchAll() as $emps){
echo "<li>" . $emps["FirstName"] . $emps["LastName"] . "</li>";
}
echo '</ul>';
$stmt = null;
}
catch (Exception $e) {
echo "Error";
echo $e->getMessage();
}
?>
I even have the program echo the SQL query and I copy that into MySQL and it still works. Could it be a simple syntax error or is it the table joins that im performing?
Also im certain that the program is contacting the database correctly because I have other similar PHP files working properly like this one:
<?php
try {
$sql = 'SELECT department.Name FROM adventureworks.department';
$stmt = $dbh->prepare($sql);
$stmt->execute();
echo '<ul>';
foreach ($stmt->fetchAll() as $depts) {
echo "<li>" . $depts["Name"] . " -> (" .
"<a href='deptEmps.php?deptID=" . $depts['deptID']
. "'>Employees </a>)" . "</li>\n";
}
echo '</ul>';
$stmt = null;
}
catch (Exception $e) {
echo "Error";
echo $e->getMessage();
}
?>
The problem with the PHP script was that I was not specifying which tables to select from. This was harder than it should have been since the syntax above returned data in MySQL which was the database I was accessing, The correct PHP script that is working can be found below:
Working PHP:
<?php
try {
$sql = 'SELECT contact.FirstName,contact.LastName ';
$sql .= 'FROM adventureworks.employeedepartmenthistory ';
$sql .= 'JOIN adventureworks.employee USING(EmployeeID) ';
$sql .= 'JOIN adventureworks.contact USING(ContactID) ';
$sql .= 'WHERE DepartmentID = 2';
$stmt = $dbh->prepare($sql);
$stmt->execute();
echo $sql;
echo '<ul>';
foreach ($stmt->fetchAll() as $emps){
echo "<li>" . $emps["FirstName"] . $emps["LastName"] . "</li>";
}
echo '</ul>';
$stmt = null;
}
catch (Exception $e) {
echo "Error";
echo $e->getMessage();
}
?>
I was wrong that the tables would have been assumed through the JOIN in PHP as they are in MySQL.
So I have this PHP code:
Note: I do use mysqli_connect() further up.
$result = mysqli_query($con,"SELECT * FROM `smf_messages` WHERE `id_board` = 18");
if(!$result) {
echo "<center><p>Couldn't fetch news posts. Error code 2.</p></center>";
mysqli_close($con);
} else {
$posts = array();
$topicbdy = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$posts[$row['id_topic']] = $row['id_topic'];
$topicbdy[$row['id_msg']] = $row['id_msg'];
}
$display = max($posts);
$display2 = min($topicbdy);
$qry = "SELECT * FROM `smf_messages` WHERE `id_board` = 18 AND `id_topic` = " . $display . " AND `id_msg` = " . $display2;
$result2 = mysqli_query($con,$qry);
//echo $qry;
if(!$result2) {
echo "<center><p>Couldn't fetch news posts. Error code 3.</p></center>";
} else {
while($show = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
echo "<center><h1>" . $show['subject'] . "</h1></center><br /><br />";
echo "<center>" . $show['body'] . "</center><br />";
}
}
mysqli_free_result($result);
mysqli_free_result($result2);
mysqli_close($con);
It's supposed to get the latest topic out of the database for my SMF-based forum from the news board, by getting the highest topic id, but the lowest post id. It seems to be doing the query just fine, as I don't get any errors, but it doesn't show the subject or body. What should I do?
Your $result variable is wrong for second query fetch. For your second query
while($show = mysqli_fetch_array($result,MYSQLI_ASSOC))
Should be
while($show = mysqli_fetch_array($result2,MYSQLI_ASSOC))
^
I have a simple program that I am trying to implement some sort of pagination/capability to navigate through individual records in a MySQL database. The code itself calls a function that returns an associative array so that the records may be navigated sequentially in the case of non-sequential indices being made by deletes.
function getKeys($handle, $user, $password) {
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation_ID from Workstation";
$result = $conn -> query($sql);
$resultArray = array();
while ( $row = $result -> fetch()) {
$resultArray[] = $row;
}
$conn = null;
return $resultArray; }
I am attempting to store the result from this function into a variable and from there try to increment that variable for use in an other function:
$Keys = getKeys($dsn,$un,$pw);
$i = 0;
$currID = $Keys[$i][0];
$row = getResultSet($dsn,$un,$pw,$currID);
I would then use the $row to display the current workstation :
echo "<hr class='viewHR'>";
echo "</br></br><div class='viewFormat'>";
echo "<form name = 'updateWorkstationForm' action ='updateWorkstation.php' method ='post'>";
echo "<b>Workstation Name:</b><br><input type = 'Textbox' name = 'pcName' value = '" . $row['Workstation_Name'] . "'/></br>";
echo "<b>Serial Number: </b><br> <input type = 'Textbox' name = 'SN' value = '" . $row['Serial_Number'] . "'/></br>";
echo "<b>Model</b></br>";
echo "<select name ='modelSelect'>";
echo "<option value = '".$row['Model_ID'] . "'>" . $row['Model'] . "</option>";
echo "</select></br>";
echo "<b>Department</b></br>";
echo "<select name ='DepartmentSelect'>";
echo "<option value = '".$row['Department_ID'] . "'>" . $row['Department'] . " </option>";
echo "</select></br>";
I was wondering if I was going about this completely wrong or how I would approach incrementing the array's index to display each record on a click of an anchor tag or button the whole file is as follows :
<html>
<body>
<div>
<?php
$un = "xxx";
$pw = "xxxxxx";
$dsn = "mysql:host=127.0.0.1;dbname=xxxxxxxxxxx";
$Keys = getKeys($dsn,$un,$pw);
$i = 0;
$currID = $Keys[$i][0];
$row = getResultSet($dsn,$un,$pw,$currID);
echo "<hr class='viewHR'>";
echo "</br></br><div class='viewFormat'>";
echo "<form name = 'updateWorkstationForm' action ='updateWorkstation.php' method = 'post'>";
echo "<b>Workstation Name:</b><br> <input type = 'Textbox' name = 'pcName' value = '" . $row['Workstation_Name'] . "'/></br>";
echo "<b>Serial Number: </b><br> <input type = 'Textbox' name = 'SN' value = '" . $row['Serial_Number'] . "'/></br>";
echo "<b>Model</b></br>";
echo "<select name ='modelSelect'>";
echo "<option value = '".$row['Model_ID'] . "'>" . $row['Model'] . "</option>";
echo "</select></br>";
echo "<b>Department</b></br>";
echo "<select name ='DepartmentSelect'>";
echo "<option value = '".$row['Department_ID'] . "'>" . $row['Department'] . "</option>";
echo "</select></br>";
echo "<b>Room</b></br>";
echo "<select name ='RoomSelect'>";
echo "<option value = '".$row['Room_ID'] . "'>" . $row['Room'] . "</option>";
echo "</select></br>";
echo "<b>Property Status</b> </br>";
echo "<select name = 'propertyStatus'>";
echo "<option value = '".$row['Property_Status_ID'] . "'>" . $row['Property_Status'] . "</option>";
echo "</select></br>";
if ($row['Property_Status'] != "Owned"){
echo "<b>Lease Company:</b> ";
echo "<select name = leaseSelect>";
echo "<option value = '" . $row['Lease_Info_ID'] ."'>Company:" . $row['Company'] . ", Start: " . $row['Start_Date'] . "End: " .$row['End_Date'] . "</option>";
echo "</select></br>";
}
echo "<b>Cart</b></br>";
echo "<select name ='cartSelect'>";
echo "<option value = '".$row['Cart_ID'] . "'>" . $row['Cart_Type'] . "</option>";
echo "</select></br>";
echo "<b>Workstation Comments: </b><br> <Textarea rows='5' cols='60' name = 'wsComments'> ". $row['Workstation_Comment'] . " </Textarea></br>";
echo "<b>Location Comments: </b><br> <Textarea rows='5' cols='60' name = 'locComments'> ". $row['Workstation_Comment'] . " </Textarea></br>";
echo "<input type = 'submit' value = 'Update' />";
echo "<input type = 'button' value = 'Cancel' onclick = 'location.reload(this);' />";
echo "</form>";
echo "</div>";
/*Function to return a parallel array. This is so that non-sequential records in the database may be described sequentially with the help of an array's indices*/
function getKeys($handle, $user, $password) {
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation_ID from Workstation";
$result = $conn -> query($sql);
$resultArray = array();
while ( $row = $result -> fetch()) {
$resultArray[] = $row;
}
$conn = null;
return $resultArray;
}
function getResultSet($handle, $user, $password, $ID) {
$resultSet = "";
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation.Workstation_ID,Workstation.Model_ID,Workstation.Property_Status_ID,workstation.Lease_Info_ID, Workstation.Workstation_Name, Workstation.Serial_Number, Model.Model, Department.Department,Room.Room,Property_Status.Property_Status,Lease_Info.Start_Date,Lease_Info.End_Date,Lease_Info.Company,Lease_Info.Lease_Comment,Cart.Cart_Type,Workstation.Workstation_Comment,Workstation.Location_Comment from Workstation INNER JOIN Model ON Workstation.Model_ID = Model.Model_ID INNER JOIN Department ON Workstation.Department_ID = Department.Department_ID INNER JOIN Room ON Workstation.Room_ID = Room.Room_ID INNER JOIN Property_Status ON Workstation.Property_Status_ID = Property_Status.Property_Status_ID INNER JOIN Lease_Info ON Workstation.Lease_Info_ID = Lease_Info.Lease_Info_ID INNER JOIN Cart ON Workstation.Cart_ID = Cart.Cart_ID where Workstation_ID = :ID";
$pstmt = $conn -> prepare($sql);
if(!$pstmt) {
echo "Error preparing the statement. Error: (" . $conn -> ErrorInfo() . ")";
}
$pstmt -> bindParam(':ID', $ID);
try {
$pstmt -> execute();
}
catch(PDOException $e) {
echo "Failed to execute prepared Statement. Error: (" . $e -> getmessage() . ")";
}
$resultSet = $pstmt -> fetch();
return $resultSet;
$conn = null;
}
?>
</div>
</body>
</html>
Any criticism, insight, or pointers would be greatly appreciated.
You shouldn’t be fetching all records if you only intend to display a subset, or just one.
To paginate, use the LIMIT clause. So, if you split records into pages of ten, then to get the first page your query would be:
SELECT * FROM workstations LIMIT 0,10
Where the first number is the offset, and the second number is the number of records after the offset you wish to fetch. To fetch the second page, you’d change the limit clause to be LIMIT 10,10; to fetch the third page LIMIT 20,10, and so on. The PHP equation is:
$offset = (($page - 1) * $records_per_page);
The page value can come from a $_GET variable, like http://www.example.com/?page=1.
Secondly, if you’re only wanting to display one record, then fetch that one:
SELECT * FROM workstations WHERE id = ? LIMIT 1
Pass the ID via a $_GET parameter again, and use PDO to bind it to avoid SQL injection vulnerabilities:
<?php
$sql = "SELECT * FROM workstations WHERE id = :id LIMIT 1";
$sth = $db->prepare($sql);
$sth->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$sth->execute();
$row = $sth->fetchObject();