I have an Access database that has been converted to MySQL. I have a table, Contacts, with fields 'EmailAddress', 'HideEmailAddress', 'FaxNumber', 'HideFaxNumber', 'PhoneNumber', and 'HidePhoneNumber'. The hide fields are all checkboxes, so have values of 1 or 0, with 1 being TRUE.
I need, either in my MySQL Select statement or in my PHP query, to be able to not show the information if the hide field has a value of 1. Also, it's pretty common that only one of the three fields will be marked as hide, so I can't do a blanket "if any of these are 1 hide all of them.' I need to output the query to a webpage, and either show or hide the three fields above depending on the value of the hide field for each column. My SELECT statement is retrieving all six values, and the PHP is turning it into an array, but I don't think anything with array comparison will help here.
I just have no idea what I should be doing here. I've been searching for a couple of days now and nothing seems to come close to what I need. I have a VERY ad-hoc if-elseif-else running in my PHP loop in order to get it done by the deadline, but that requires 9 or 12 different statements, and I'm sure there's a better way to do this.
Here's my code. I've chopped it up a lot from the original query, but that query does work, so if there are typos here, it's from the chop-up. I just can't figure out how to suppress a field based on the value of another field. This is also why I have the two AS statements in the SELECT statement - in the original query, there's information coming from five different tables and there's "FaxNumber" and "EmailAddress" in both of them. I left the AS in just in case it changes things.
<?php
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die('Error connecting to MySQL server.');
$query = 'SELECT Contact.CompanyID, Contact.WebContact, Contact.FirstName, Contact.LastName, Contact.WorkPhone, Contact.HidePhoneNumber, Contact.FaxNumber AS ConFaxNumber, Contact.HideFaxNumber, Contact.EmailAddress AS ConEmailAddress, Contact.HideEmailAddress FROM Contact WHERE TDAT_Contact.WebContact = "1"';
mysqli_query($dbc, $query);
if($r = mysqli_query($dbc, $query)) {
while ($row = mysqli_fetch_array($r)) {
if(($row['HidePhoneNumber'] == 1) && ($row['HideFaxNumber'] == 1)) {
echo '<hr><div align="query"><span class="strong">Contact:</span> ' . $row['FirstName'] . ' ' . $row['LastName'] . '<br /><br /><span class="strong">Direct Email Address: </span>' . $row['ConEmailAddress'] . '</div>';
} elseif($row['HidePhoneNumber'] == 0) && ($row['HideFaxNumber'] == 0) {
echo '<hr><div align="query"><span class="strong">Contact:</span> ' . $row['FirstName'] . ' ' . $row['LastName'] . '<br /><span class="strong">Direct Telephone: </span>' . $row['WorkPhone'] . '<br /><span class="strong">Direct Fax: </span>' . $row['ConFaxNumber'] . '<br /><span class="strong">Direct Email Address: </span>' . $row['ConEmailAddress'] . '</div>';}
}
...
else { // Query didn't run.
echo '<p style="color: red;">Could not retrieve the data because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
}}
mysqli_close($dbc); // Close the connection.
?>
<?php
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die('Error connecting to MySQL server.');
$query = 'SELECT Contact.CompanyID, Contact.WebContact, Contact.FirstName, Contact.LastName, Contact.WorkPhone, Contact.HidePhoneNumber, Contact.FaxNumber AS ConFaxNumber, Contact.HideFaxNumber, Contact.EmailAddress AS ConEmailAddress, Contact.HideEmailAddress FROM Contact WHERE TDAT_Contact.WebContact = "1"';
mysqli_query($dbc, $query);
if($r = mysqli_query($dbc, $query)) {
while ($row = mysqli_fetch_array($r)) {
echo '<hr><div align="query"><span class="strong">Contact:</span> ' . $row['FirstName'] . ' ' . $row['LastName'] . '<br />';
if ($row['HidePhoneNumber'] == 0) {
echo '<span class="strong">Direct Telephone: </span>' . $row['WorkPhone'] . '<br />';
}
if ($row['HideEmailAddress'] == 0) {
echo '<span class="strong">Direct Email Address: </span>' . $row['ConEmailAddress'] . '<br />';
}
if ($row['HideFaxNumber'] == 0) {
echo '<span class="strong">Direct Fax: </span>' . $row['ConFaxNumber'];
}
echo '</div>';
}
} else { // Query didn't run.
echo '<p style="color: red;">Could not retrieve the data because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
mysqli_close($dbc); // Close the connection.
You can do it in mysql and avoid extra php coding
something like this assuming the Hide fields are booleans
$query = 'SELECT Contact.CompanyID, Contact.WebContact, Contact.FirstName,Contact.LastName,
case when Contact.HidePhoneNumber then '' else Contact.WorkPhone end as WorkPhone,
case when Contact.HideFaxNumber then '' else Contact.FaxNumber end AS ConFaxNumber,
case when Contact.HideEmailAddress then '' else Contact.EmailAddress and AS ConEmailAddress FROM Contact WHERE TDAT_Contact.WebContact = "1"';
then on php you just
if($r = mysqli_query($dbc, $query)) {
while ($row = mysqli_fetch_array($r)) {
echo '<hr><div align="query"><span class="strong">Contact:</span> ' . $row['FirstName'] . ' ' . $row['LastName'] . '<br /><span class="strong">Direct Telephone: </span>' . $row['WorkPhone'] . '<br /><span class="strong">Direct Fax: </span>' . $row['ConFaxNumber'] . '<br /><span class="strong">Direct Email Address: </span>' . $row['ConEmailAddress'] . '</div>';
}
}
Break your html output in small pieces, observe the common patterns, and factorize it in functions:
function hide($field, $label, $row){
if ($row['Hide'.$field] == 0)
echo '<span class="strong">'.$label.'</span>'.$row[$field].'<br/>';
}
$hiddenfields = array ('EmailAddress' => 'Email Address', 'PhoneNumber' => 'Direct Telephone' /* etc. */);
foreach($hiddenfields as $field => $label)
hide($field,$label,$row);
This should get you started.
You are using AND operator(($row['HidePhoneNumber'] == 1) && ($row['HideFaxNumber'] == 1) which means both conditions must be true to execute the conditional code.To resolve your problem you can use 'nested loop' within your while loop and check expressions for example:
$conditions=array("0"=>"phonenumber","1"=>"fax","2"=>"email") //associative array
for($i=0;$i<count($conditions);$i++){
if($row[$conditions[$i]]==1){
echo $row.[$conditions[$i]];
}
else{
echo "user doesn't want to share this information";
}
}
if condition returns 1 it will echo associated array member.
Related
I want to check for no result in MySQL query and return a no result message to the user. How do I integrate it with my current code?
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)) {
echo '<div class="mydiv">';
if($row['photo']){
echo "<p>" . '<span class="glyphicon" aria-hidden="true"></span>' . '</p>' . '<p>' . "<img src=http://localhost:8888/example/images/" . $row['photo'] . "><hr>";
}else
echo '<p>' . '<span class="glyphicon" aria-hidden="true"></span>' . $row['message'] . '</p>';
echo '<p>' . '~' . $row['username'] . '</p>';
echo '<p>' . $row['datetime'] . ' ' .'(UTC)' . '</p>';
echo '</div>';
}
I want a "no result" message to show up when there are no records found. How do I integrate it in my existing code. Please advise.
if ($row = mysql_num_rows($result) == 0){
echo "<h3>There are no result found.</h3>";
}
if ($result = mysql_query($sql) && mysql_num_rows($result) > 0) {
// there are results in $result
// whatever you want to do with your results
} else {
// no results
echo "<h3>There are no results found.</h3>";
}
A form sends name, topic, email, and blurb to MySQL db. Email is not a required field, but if it is !empty I want to include it as the name and echo the row data.
This is my idea so far:
if (!empty($_POST['email']))
{
$row['name'] = "<A href='mailto:' . $_POST['email'] . '>' . $_POST['name'] . '</A>";
}
else
{
$row['name'] = $_POST['name'];
}
I am having trouble sorting out the coding for the email/name any help please. And the rows will be:
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td><Posted by : ' . $row['name'] . ' on ' . $row['date'] . '<br />
Topic : ' . $row['topic'] . '<br />Thoughts : ' . $row['thoughts'] . '</td>';
echo "</tr>";
Not very well sorted yet, help please :-) thanks.
are you want that if the email is not empty then you want to replace it with name and echo it? if yes then try the below code..
if (!empty($_POST['email']))
{
$row['name'] =$_POST['email'];
$row['name']="<A href='mailto:' . $_POST['email'] . '>' . $_POST['name'] . '</A>";
}
else
{
$row['name'] = $_POST['name'];
}
New to PHP, first post on stackoverflow... From the tutorials I've read, I'm 'somewhat' protected from injection, and I know I'm passing my variables correctly from my search form. The issue I'm having is when I attempt to read the results; I receive an "undefined index" error for them and I have no idea why. I've been staring at this and reading for the last day and am about to pull out my hair. Would someone be able to point me in the right direction? and yes, i know, don't use root; this is purely for demo and hosted locally until i have everything smoothed out. Thanks for any help! -Jason
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("%[a-zA-Z0-9_-]%", $_POST["booktext"])){
$searchvalue=$_POST["booktext"];
// create connection
$user="root";
$password="";
$database="bookcat_data";
$host="127.0.0.1:3306";
$searchtype=$_POST["searchtype"];
$con=mysqli_connect($host, $user, $password, $database);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT Book.BookID, Book.Title, Book.AuthorSort, Publisher.Publisher, Book.PublishDate, Book.ISBN FROM ((Book LEFT JOIN Edition ON Book.EditionID = Edition.EditionID) LEFT JOIN PrintedBy ON Book.PrintedByID = PrintedBy.PrintedByID) LEFT JOIN Publisher ON Book.PublisherID = Publisher.PublisherID WHERE " . $searchtype . " LIKE '%" . $searchvalue . "%' ORDER BY Book.Title;";
$result=mysqli_query($con,$sql);
switch($searchtype) {
case "Book.Title":
$header="Book Title";
break;
case "Book.AuthorSort":
$header="Author";
break;
}
echo '<title>' . $header . ' Search for "' . $searchvalue . '"</title>';
echo '<h3 align="center">' . $header . ' Search for "' . $searchvalue . '" - Sorted by Title</h3>';
echo '<table cellpadding="3" cellspacing="2" border="1" id="catalogs" class="center">';
echo '<tr><th>Book Title</th><th>Author</th><th>Publisher</th><th>Publish Date</th><th>ISBN</th>';
while($row=mysqli_fetch_array($result)) {
$BookID=$row['Book.BookID'];
$BookTitle=$row['Book.Title'];
$Author=$row['Book.AuthorSort'];
$Publisher=$row['Publisher.Publisher'];
$PublishDate=$row['Book.PublishDate'];
$ISBN=$row['Book.ISBN'];
echo '<tr>';
echo '<td><a href=\'bookinfo.php?id=$BookID\'>' . $BookTitle . '</td>';
echo '<td>' . $Author . '</td>';
echo '<td>' . $Publisher . '</td>';
echo '<td>' . $PublishDate . '</td>';
echo '<td>' . $ISBN . '</td>';
echo '</tr>';
}
echo '</table>';
mysqli_free_result($result);
mysqli_close($con);
}
}
else{
echo "<p>Please enter an appropriate search</p>";
}
}
SQL queries return the column names without the table prefix. Remove this prefix when accessing your array elements. So $row['BookID'] instead of $row['Book.BookID'].
I have a session that is supposed to carry a variable from one page to another. The session is set, however it does not have the correct value, I need this session to dynamically change.
Here's the code for the viewing page:
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$query = "SELECT username FROM kaoscraft_user WHERE user_id = '" . $_SESSION['user_id'] . "'";
$data = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($data);
$username1 = $row['username'];
// Grab the pm data from the database
$query = "SELECT `to`, `from`, rank, gender, picture, title, msg FROM kaoscraft_pm WHERE `to` = '$username1' ORDER BY msg_id DESC";
$data = mysqli_query($dbc, $query);
$gender = $row['gender'];
while ($row = mysqli_fetch_array($data)) {
session_start();
$reply = $row['from'];
$_SESSION['reply'] = $row['from'];
echo '<div class="viewpost">';
echo '<div class="vpside">';
if(!empty($row['picture'])) {
echo '<img class="pictest" src="' . MM_UPLOADPATH . $row['picture'] . '" alt="' . MM_UPLOADPATH . 'nopic.png' . '" />';
}
if(!empty($row['from'])) {
echo '<p>From:<br />' . $row['from'] . '</p>';
echo 'Reply';
}
if(!empty($row['rank'])) {
echo '<p>Rank:<br />' . $row['rank'] . '</p>';
}
if(!empty($row['gender'])){
echo '<p>Gender:<br /> ' . $row['gender'] . '</p>';
}
echo '</div>';
if(!empty($row['title'])) {
echo'<h4><u>' .$row['title']. '</u></h4>';
}
if(!empty($row['msg'])) {
echo '<p class="">' . $row['msg'] . '</p>';
}
echo '<div class="sig">';
if(!empty($row['bio'])) {
echo '<p>' . $row['bio'] . '</p>';
}
echo '</div>';
echo '</div><br />';
}
mysqli_close($dbc);
?>
Yes, the query had been executed, and yes row is set.
Here's the carry over script:
if (isset($_SESSION['reply'])) {
echo 'value=' . $_SESSION['reply'];
}
Mind you this is a test script and not the script I will actually be using, just in-case you were wondering. and in the second script it is a SNIPPET not the whole code that is why you do not see session_start();
$query = "SELECT * FROM `status_info_private` WHERE `id`=$id ORDER BY `Status_Date` DESC LIMIT 100";
if ($query_run = mysql_query($query)) {
while ($rows = mysql_fetch_array($query_run)) {
echo '<font color="#009900" > ' . $rows['Name'] . ' ' . ' Says :' . '</font><br/>';
echo '<p align="justify> ' . $rows['Private_status'] . '<br/>';
echo '<p align="right">' . $rows['Status_Date'] . '<br/>';
$like = $rows['Like'];
$unlike = $rows['Unlike'];
}
}
I think everything is correct in the piece of code. But still I am unable to get the output under the column titled as "Private_status". The above code is producing everything correctly except the message under cols "Private_status". I have already checked the spelling of the col name & there is no error in that part.
So, Please tell me what exactly is missing ?
first close your <p> tags and then do a print_r to check what is in $rows
..
Also, start using PDO or mysqli
$query = "SELECT * FROM `status_info_private` WHERE `id`=$id ORDER BY `Status_Date` DESC LIMIT 100";
if ($query_run = mysql_query($query)) {
while ($rows = mysql_fetch_array($query_run)) {
echo '<a href="view_profile.php?id=' . $id . '" color="#009900" > ' . $rows['Name'] . ' ' . ' Says :' . '</a><br/>';
echo '<p align="justify"> ' . $rows['Private_status'] . '</p>';
echo '<p align="right">' . $rows['Status_Date'] . '</p>';
$like = $rows['Like'];
$unlike = $rows['Unlike'];
}
}