Statements after while loop not executing - php

I am trying to remove a user from the mailing list right before I perform the emailing to my users. However, the code responsible for this within the second while loop is not executing.
Can somebody see why this is?
<?php
$query = "SELECT * FROM remove_request";
$result = mysqli_query($dbc,$query);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$query = "DELETE FROM mail_table WHERE first_name='" . $row["first_name"]
. "' AND last_name='" . $row["last_name"]
. "' AND email_address='" . $row["email_address"] . "'";
$result = mysqli_query($dbc,$query);
echo $row["first_name"] . ' has been removed from the mail list.';
}
}
$query = "SELECT * FROM mail_table";
$result = mysqli_query($dbc,$query) or die('Error querying database');
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
mail($row["email_address"],$subject,$message,$headers);
echo 'email sent to ' . $row["first_name"] . "\n";
}
}
mysqli_close($dbc);
?>

Related

How to update database's value after pressing button?

I am currently working on my assignment, I am trying to create a ban system for users, I wanna update the value of Deleted in my database to 1 whenever I press the submit button, I tried many on youtube videos but has not given any process
$id = $_SESSION['UserID'];
$query = "SELECT * FROM Users WHERE UserID='$id'";
$result = mysqli_query($link, $query);
$row2 = mysqli_fetch_assoc($result);
if ($row2['Admin'] == 0) {
echo '<div class="alert alert-warning" role="alert">
Unfortunately you do not have access to this page
</div>';
}
else {
$query = " SELECT * FROM Users WHERE Admin = 0";
$result = mysqli_query($link, $query);
echo '<div class="container">';
echo '</div>';
echo '<div class="container"><table class="table table-primary table-hover">';
echo '<tr><th>' . 'NameID' . '</th><th>' . 'Name' . '</th><th>' . 'Email' . '</th><th>' . '</tr>';
while ($row2 = mysqli_fetch_assoc($result)) {
echo '<tr><td>' . $row2['UserID'] . ' </td><td> ' . $row2['FirstName'] . ' ' . $row2['LastName'] . ' </td><td> ' . $row2['EMail'] . ' </td><td> '
. '<input type="submit" name="submit" class="btn btn-primary btn-xs" value="BAN">' . ' </td></tr>';
}
if (isset($_POST['submit'])) {
echo '</table>' . '</div>';
$id = $_SESSION['UserID'];
$query = "SELECT * FROM Users WHERE UserID='$id'";
$result = mysqli_query($link, $query);
if ($_POST['submit']) {
$query2 = "UPDATE `Users` SET `Deleted` = '1' WHERE `Users`.`UserID` ='$id'";
}
}
}
You define $query2 but never execute it. This is a common mistake.
Tip: Don't declare SQL as strings and then run it later, get in the habit of supplying the query as a direct argument to prepare().
For example:
$stmt = $link->prepare('UPDATE `Users` SET `Deleted` = '1' WHERE `Users`.`UserID`=?');
$stmt->bind_param('i', $id);
$stmt->execute();
You don't run the $query2, do it like this
if ($_POST['submit']) {
$query2 = "UPDATE `Users` SET `Deleted` = '1' WHERE `Users`.`UserID` ='$id'";
mysqli_query($link, $query2);
}

PHP not displaying database on website

I've compiled the following PHP and HTML, what I want to do is connect my WAMP database to my webpage, it's a simple task but the output i receive is displayed in the picture below, can somebody show me where i went wrong?
<?php
//Step 1
$db = mysqli_connect('localhost', 'root', '', 'hospital') or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<h1>
PHP connect to MySQL
</h1>
<?php
//Step 2
$query = "SELECT * FROM patients";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
while($row = mysqli_fetch_array($result)){
echo $row['id'] . ' ' . $row['patient_name']. ' ' . $row['check_in_date'] . ' ' . $row['room_number'] . ' ' . $row['bed_number'] . ' ' . $row['notes'] . '<br />';
}
?>
</body>
</html>
PHP and HTML error
I have found some errors in that code
$query = "SELECT * FROM patients";
You need to add the semicolon a the end of the query code here, so:
$query = "SELECT * FROM patients;";
Then we have this
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
while($row = mysqli_fetch_array($result)){
echo $row['id'] . ' ' . $row['patient_name']. ' ' . $row['check_in_date'] . ' ' . $row['room_number'] . ' ' . $row['bed_number'] . ' ' . $row['notes'] . '<br />';
}
This should work
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
$patientname = $row['patient_name']; //do this with every variable you have
echo "$id $patientname";
}
EDIT: Also, change this
$db = mysqli_connect('localhost', 'root', '', 'hospital') or die('Error connecting to MySQL server.');
with this
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "hospital";
$db = mysqli_connect($dbhost,$dbuser,$dbpass) or die ("dbconn");
mysql_select_db($dbname,$db) or die ("msq");
You dont need to assign
$row = mysqli_fetch_array($result); as you are assigning it inside the while loop
EDITED ANSWER
Build a sperate array from the rows and then loop over that, this way you will have more flexibility to add to or edit the results before displaying them
//Step 2
$query = "SELECT * FROM patients";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
$rows = array();
while($row = mysqli_fetch_array($result)){
$rows[] = $row;
}
foreach($rows as $r) {
echo $r['id'] . ' ' . $r['patient_name']. ': ' . $r['check_in_date'] . ' ' . $r['room_number'] . ' ' . $r['bed_number'] . ' ' . $r['notes'] . '<br />';
}

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!

Can't display database records

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 = "Нямате съобщения :(";
}

Variable not recognised in INSERT but working in SELECT

Basically I am using the variable $shopid to recognise which shop has been chosen. I am now trying to create a comment system to enable each shop page to be commented on. My SELECT query is recognising $shopid and enabling me to use it, when I try to use the same variable in my INSERT, it simply posts 0.
<?php
database connection
session_start();
if (isset($_SESSION['logged'])){
$s_userID = $_SESSION['userID'];
$shopid = $_GET['page_id'];
$str_shops = '';
//bring shop data
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE shopID = '$shopid'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<div class='result'><strong>" .
$row['image1'] . "<br><br>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br>" .
$row['website'] . "<br><br>" .
$row['openinghours'] . "<br><div class='justifytext'>" .
$row['more'] . "<br><br></div><strong>What do they sell?</strong><br><br><div class='justifytext'>" .
$row['sold'] . "<br><br></div></div>";
}
//post comment
mysqli_select_db($db_server, $db_database);
$comment = $_POST['comment'];
if ($comment != '') {
$query = "INSERT INTO comments (userID,shopID,comment) VALUES ('$s_userID', '$shopid', '$comment')";
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server));
$commentmessage = "Thanks for your comment!";
}
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server)); $i = 0;
while($row = mysqli_fetch_array($result)){ $i++;
$str_comments.= "<p><div id='displaycomments'>" . $row['username']. ", " .
$row['commdate'] . ": <br>" .
$row['comment'] . "</div>";
}
}
echo $str_shops;
echo $commentmessage;
echo $str_comments;
mysqli_close($db_server);
?>
Can anyone see why this isn't working? I'm not getting an error, it is simply adding 0 to the shopID column in my table.
My guess would be that your shopID column would be of INT datatype and you are passing a string to it in your insert statement, thats why 0 is being stored.Try again by removing the single quotes around $shopid, like this-
INSERT INTO comments (userID,shopID,comment) VALUES ('$s_userID', $shopid, '$comment')"
^^^^^^^ remove the single quotes

Categories