Can't display database records - php

I want to echo sql database records in my page and I am using this code. When I run it doesn't display the result from the db. I have records in the database that match the criteria. I am new in php and sql so please tell where I have mistakes.
session_start();
if (!isset($_SESSION['name'])) {
header('Location:vhod.php');
exit;
}
$pageTitle = 'СЪОБЩЕНИЯ';
include 'includes/header.html';
$email = $_SESSION['email'];
$name = $_SESSION['name'];
include 'php/db_connect.php';
$msgs = '';
$query = 'SELECT `timestamp`, `to`, `sender`, `subject`, `msg` FROM msg WHERE `to`="$name"';
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$msgs = "ДАТА: " . $row["timestamp"] . " >> От: " . $row["sender"] . " >> Тема: " . $row["subj"] . " >> Съобщение: " . $row["msg"] . "<br>";
}
} else {
$msgs = "Нямате съобщения :(";
}

try modifying the lower part of your code like this.
$msgs = '';
$query = "SELECT * FROM msg WHERE to=$name";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$msgs = "ДАТА: " . $row['timestamp'] . " >> От: " . $row['sender'] . " >> Тема: " . $row['subj'] . " >> Съобщение: " . $row['msg'] . "<br>";
}
} else {
$msgs = "Нямате съобщения :(";
}

Related

simplify php/mysql nested calls

I have a mysql table which I'm trying to turn into jQuery listview widgets. The part that I'm having trouble with is how best to extract the info from the table without doing multiple queries on the db itself. I have the following code which works:
global $conn;
$sql = "SELECT `id` FROM `implantFamilies` WHERE `familySelector` = '" . $_POST['implantFamily'] . "'"; //need to sanitise this
$result = $conn->query($sql);
if ($result->num_rows == 1) {
while($row = $result->fetch_assoc()) {
$familyId = $row["id"];
}
} else {
die("Error: " . $result->num_rows . " family groups in result. Alert administrator.");
}
?>
<form class="ui-filterable">
<input id="filterBasic-input" data-type="search">
</form>
<?php
$sql = "SELECT DISTINCT `familySection` FROM `implants` WHERE `familyGroupId` = '" . $familyId . "'";
$sections = $conn->query($sql);
if ($sections->num_rows > 0) {
while ($sectionRow = $sections->fetch_assoc()) {
$output .= "<b>" . $sectionRow["familySection"] . "</b><br>";
//DISPLAY COLLAPSIBLE DIV HERE
$sql = "SELECT DISTINCT `sectionHeading` FROM `implants` WHERE `familyGroupId` = '" . $familyId . "' AND `familySection` = '" . $sectionRow["familySection"] . "'";
$dividers = $conn->query($sql);
if ($dividers->num_rows > 0) {
while ($headingRow = $dividers->fetch_assoc()) {
$output .= "<i>" . $headingRow["sectionHeading"] . "</i><br>";
//DISPLAY list-divisers DIV HERE
$sql = "SELECT `reference`, `description`, `filterText`, `requiresLot` FROM `implants` WHERE `familyGroupId` = '" . $familyId . "' AND `familySection` = '" . $sectionRow["familySection"] . "' AND `sectionHeading` = '" . $headingRow["sectionHeading"] . "'";
$implants = $conn->query($sql);
if ($implants->num_rows > 0) {
while ($implantRow = $implants->fetch_assoc()) {
$output .= $implantRow["description"] . "<br>";
//DISPLAY implants DIV HERE
}
} else {
$output = "0 results";
}
}
} else {
$output = "0 results";
}
}
} else {
$output = "0 results";
}
$conn->close();
echo $output;
On the first lot of (simple) data which I've put into the table, this code executes 23 mysql queries. There must be a simpler way!

Cant get table to update, delete and add with an extra code

So What Im trying to do is have the user add a code to a form, and fill the form out, A to add to the table, D to delete, U to update... The delete isnt working, neither is the insert, is it my logic? also I want to print the table only once, and sometimes it does it twice... any advice?
$Code=$_POST["Code"];
if ($Code == "A")
{
$sql = "INSERT INTO movieDATA values ('$idno', '$Name', '$Genre', '$Starring', '$Year', '$BoxOffice')";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "D")
{
$sql = "DELETE FROM movieDATA WHERE IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "U")
{
$sql = "UPDATE movieDATA SET Name = '$Name', Genre = '$Genre', Starring = '$Starring', Year = '$Year', BoxOffice = '$BoxOffice' where IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
?>

SQL Edits first option only

This is the code from our handle page we are trying to edit our database in phpmyadmin but can seem to only edit our first entry even though we clicked on other entries' edit button
require 'dbfunction.php';
$con = getDbConnect();
$crew_id = $_POST["crew_id"];
$CrewName = $_POST["CrewName"];
$CrewRank = $_POST["CrewRank"];
$StartDate = $_POST["StartDate"];
$EndDate = $_POST["EndDate"];
$PayrollNo = $_POST["PayrollNo"];
$EmployeeNo = $_POST["EmployeeNo"];
$WatchKeeping = $_POST["WatchKeeping"];
$Active = $_POST["Active"];
//$Delete = $_POST["Delete"];
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT crew_id " .
"FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
if (!mysqli_connect_errno($con)) {
$sqlQueryStr = "UPDATE crewlist SET crew_name = '$CrewName', crew_rank = '$CrewRank', start_date = '$StartDate' "
. ", end_date = '$EndDate', payroll_no = '$PayrollNo'"
. ", employee_no = '$EmployeeNo', watchkeeping = '$WatchKeeping', active = '$Active' WHERE crew_id = " . $row['crew_id'];
mysqli_query($con, $sqlQueryStr);
mysqli_close($con);
} else {
break;
}
header('Location: crewlisting.php');
}
?>
This code only edits the first entry of our database and the rest remains stagnant. This is the code from our edit page
<?php
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT * " .
"FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
echo "<tr>.<th>" . $row["crew_name"] . "<br></br>" . "</th>";
echo "<th>" . $row["crew_rank"] . "</th>";
echo "<th>" . $row["start_date"] . "</th>";
echo "<th>" . $row["end_date"] . "</th>";
echo "<th>" . $row["watchkeeping"] . "</th>";
echo "<th>" . $row["active"] . "</th>";
//echo "<td><form action=\"editcrew.php\" method=\"post\"><a href='editcrew.php?del={$row['crew_id']}'>edit</a></form></td>";
echo "<td>Edit";
echo "<td><form action=\"delete.php\" method=\"post\"><a href='crewlisting.php?del={$row['crew_id']}'>delete</a></form></td>";
}
?>
You are closing your mysqli connection in the first iteration of your loop. Move the mysqli_close($con); behind the loop.
Edit: And you also redirect to crewlist.php in the loop. If you reformat your indentation of your code, this will get obvious.
Remove mysqli_close($con) from loop:
while ($row = mysqli_fetch_array($result)) {
$sqlQueryStr = "UPDATE crewlist SET crew_name = '$CrewName', crew_rank = '$CrewRank', start_date = '$StartDate' "
. ", end_date = '$EndDate', payroll_no = '$PayrollNo'"
. ", employee_no = '$EmployeeNo', watchkeeping = '$WatchKeeping', active = '$Active' WHERE crew_id = " . $row['crew_id'];
mysqli_query($con, $sqlQueryStr);
}
header('Location: crewlisting.php');

Else statement doesn't work in option select

I am trying to implement a dropdown search option. All my search results are working. All the commands that I have assigned to if statements work, but when it does to else it deosn't work.
Here is my code:
if(isset($_REQUEST['submit'])){
$opt = $_POST['opt'];
if($opt==1){//if opt = 1
$sqle = "SELECT * FROM tbl_events WHERE title LIKE '%{$keywords}%'";
$resulte = mysql_query($sqle,$con) or die(mysql_error());
while($row=mysql_fetch_array($resulte)){
echo "<h4>" . $row['title'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}else if($opt==2){//if opt = 2
$sqls = "SELECT * FROM tbl_games WHERE games_name LIKE '%{$keywords}%'";
$results = mysql_query($sqls,$con)or die(mysql_error());
while($row=mysql_fetch_array($results)){
echo "<h4>" . $row['games_name'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}else{
echo "Your Searched keyword did not match";
}
}
What to do?
Try this: Take a flag to check if record exists.
$flag = false;
if($opt==1){//if opt = 1
$sqle = "SELECT * FROM tbl_events WHERE title LIKE '%{$keywords}%'";
$resulte = mysql_query($sqle,$con) or die(mysql_error());
if(mysql_num_rows($resulte) > 0) {
$flag = true;
while($row=mysql_fetch_array($resulte)){
echo "<h4>" . $row['title'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}
}else if($opt==2){//if opt = 2
$sqls = "SELECT * FROM tbl_games WHERE games_name LIKE '%{$keywords}%'";
$results = mysql_query($sqls,$con)or die(mysql_error());
if(mysql_num_rows($resulte) > 0) {
$flag = true;
while($row=mysql_fetch_array($results)){
echo "<h4>" . $row['games_name'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}
}
if(!$flag){
echo "Your Searched keyword did not match";
}

PHP json_encode() in while loop

I am trying to use json_encode() in a while loop while getting database results. Here is my code:
<?
$database = sqlite_open("thenew.db", 0999, $error);
if(!$database) die($error);
$query = "SELECT * FROM users";
$results = sqlite_query($database, $query);
if(!$results) die("Canot execute query");
while($row = sqlite_fetch_array($results)) {
$data = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));
sqlite_close($database);
?>
The output of this is
{"response":"lastUserID lastUser lastXPos lastYPos"}
I want it to be...
{"response":["1 Alex 10 12", "2 Fred 27 59", "3 Tom 47 19"]}
etc.
So I want the json_encode() function to put ALL users into the array rather than the last one. How would I do this? Thanks
Try:
<?
$database = sqlite_open("thenew.db", 0999, $error);
if(!$database) die($error);
$query = "SELECT * FROM users";
$results = sqlite_query($database, $query);
if(!$results) die("Canot execute query");
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));
sqlite_close($database);
?>
Change this
while($row = sqlite_fetch_array($results)) {
$data = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
to
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
Push each user to an array:
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));

Categories