I have successfully pulled data from mySql into the message of the html email. But after several attempts, I'm unable to add a two break lines after the 10th record. Any assistance would be wonderful.
$sorc325sql = "Select * ".$sorc325sql2;
echo "<br>325sql=".$sorc325sql."<br><br>";
$sorc325res = mysqli_query($connectXXX, $sorc325sql) or die(mysqli_error($connectXXX));
if (mysqli_num_rows($sorc325res) < 1) {
$display_block = "<p><em>No topics exist.</em></p>";
} else {
while ($sorc325row = mysqli_fetch_array($sorc325res)) {
$sorc325arycustctr++;
$message .= $sorc325row['progName'].', ';
}
}
Using Mark B's idea, you need to add it to the current $sorc325arycustctr++; line
$sorc325sql = "Select * ".$sorc325sql2;
echo "<br>325sql=".$sorc325sql."<br><br>";
$sorc325res = mysqli_query($connectXXX, $sorc325sql)
or die(mysqli_error($connectXXX));
if (mysqli_num_rows($sorc325res) < 1) {
$display_block = "<p><em>No topics exist.</em></p>";
} else {
$sorc325arycustctr = 0;
while ($sorc325row = mysqli_fetch_array($sorc325res)) {
$sorc325arycustctr++;
if (! ($sorc325arycustctr % 10)) {
$message .= '<br>';
}
$message .= $sorc325row['progName'].', ';
}
}
Related
I need two print the same rows which retrieved from the db, in two different locations in same php file.
I know it is better to have a function. It tried, It doesn't work properly.
I am using the below code print the said rows/
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
echo "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
I need to print exactly the same code twice in two different location in a php file.
I think it is not a good idea to retrieve data twice from the server by pasting the above code twice.
Is there any way to recall or reprint the retrieved data in second place which I need to print.
Edit : Or else, if someone can help me to convert this to a function?
I converted this into a function. It prints only first row.
Edit 2 : Following is my function
unction getGroup($dbconn)
{
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($dbconn ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$groupData = "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
return $groupData;
You can store the records coming from the DB in array and use a custom function to render the element
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
$options = []; //store in an array
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$options[$groups['profile_gid']] = $groups['profile_gname'];
}
}
Now you can use the $options array many times in your page
echo renderElement($options);
function renderElement($ops){
$html = '';
foreach($ops as $k => $v){
$html .= "<option value={$k}>{$v}</option>";
}
return $html;
}
If the data is same for both places, put the entire string into variable, then echo it on those two places.
instead of
echo "here\n";
echo "there\n";
do
$output = "here\n";
$output .= "there\n";
then somewhere
echo $output
on two places....
Values are being stored in groups array, hence you can use a foreach loop elsewhere to get values from the array:
$groups = array();
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
echo "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
// use here
foreach($groups as $group)
{
echo $group['profile_gid'] . " ". $group['profile_gname'] . "<br/>";
}
class ProfileGroups
{
public $profile_groups_options;
public static function get_profile_groups_options($condb) {
$get_g = "SELECT * FROM profile_groups";
if( isset( $this->profile_groups_options ) && $this->profile_groups_options != '') {
return $this->profile_groups_options;
}
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$this->profile_groups_options .= "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
$this->profile_groups_options .= '<option value="">Empty - No Groups!!</option>';
}
return $this->profile_groups_options;
}
}
ProfileGroups::get_profile_groups_options($condb);
I have some code which uses odbc calls. I've had no problem with the pulling data from a MS SQL database until this bit of code. Instead of saving the string to a variable it outputs the string and saves an int 1 to the variable instead.
below is the relevant code:
$qry = 'SELECT * FROM cst_AdEssayDetails_vw WHERE AdEnrollSchedID = ?';
$essay = odbc_prepare($conn,$qry);
if(odbc_execute($essay,array($AdEnrollSchedID))){
if (odbc_num_rows($essay)>0){
while (odbc_fetch_row($essay)){
$setTopic = odbc_result($essay,'setTopic');
$essay_active = odbc_result($essay,'active');
$essay_date = date("m-d-y", strtotime(odbc_result($essay,'StartDate')));
$essayID = odbc_result($essay,'EssayID');
$EnrollSchedID = odbc_result($essay,'AdEnrollSchedID');
$intro = odbc_result($essay,'intro');
$support = odbc_result($essay,'support');
$conclusion = odbc_result($essay,'conclusion');
$essay_comment = odbc_result($essay,'comment');
$submitted = odbc_result($essay,'submitted');
$dateSubmitted = date("m-d-y", strtotime(odbc_result($essay,'dateSubmitted')));
$essay_grade = odbc_result($essay,'grade');
$AdStudentEssayID = odbc_result($essay,'AdStudentEssayID');
$topic = odbc_result($essay,'topic');
echo '<intro1>'.$intro.'</intro1>';
echo '<intro_len>'.strlen($intro).'</intro_len>';
if (1 > strlen($essay_comment)){
$essay_comment = ' ';
} else {
$essay_comment = urlencode($essay_comment);
}
if (1 > strlen($essay_grade)) {
$essay_grade = ' ';
}
if (2 < strlen($topic)){
$topic = urlencode($topic);
} else {
$topic = ' ';
}
if (2 < strlen($intro)){
$intro = urlencode($intro);
} else {
$intro = ' ';
}
if (2 < strlen($support)){
$support = urlencode($support);
} else {
$support = ' ';
}
if (2 < strlen($conclusion)){
$conclusion = urlencode($conclusion);
} else {
$conclusion = ' ';
}
echo '<setTopic>'.$setTopic.'</setTopic>';
echo '<essay_active>'.$essay_active.'</essay_active>';
echo '<essay_date>'.$essay_date.'</essay_date>';
echo '<essayID>'.$essayID.'</essayID>';
echo '<topic>'.$topic.'</topic>';
echo '<intro>'.$intro.'</intro>';
echo '<support>'.$support.'</support>';
echo '<conclusion>'.$conclusion.'</conclusion>';
echo '<essay_comment>'.$essay_comment.'</essay_comment>';
echo '<submitted>'.$submitted.'</submitted>';
echo '<dateSubmitted>'.$dateSubmitted.'</dateSubmitted>';
echo '<essay_grade>'.$essay_grade.'</essay_grade>';
echo '<AdStudentEssayID>'.$AdStudentEssayID.'</AdStudentEssayID>';
}
} else {
The output I get from this is:
'Test Introduction Paragraph
Test Supporting Paragraph
2nd test supporting paragraph
Test Conclusion Paragraph
Test Essay Topic
<intro1>1</intro1>
<intro_len>1</intro_len>
<setTopic>%3Cp%3ETest%20Topic%3C%2Fp%3E</setTopic>
<essay_active>1</essay_active>
<essay_date>01-01-70</essay_date>
<essayID>29</essayID>
<topic></topic>
<intro></intro>
<support></support>
<conclusion></conclusion>
<essay_comment>1</essay_comment>
<submitted>1</submitted>
<dateSubmitted>07-11-16</dateSubmitted>
<essay_grade></essay_grade>
<AdStudentEssayID>59</AdStudentEssayID>'
The output I expect is:
'<intro1>Test Introduction Paragraph</intro1>
<intro_len>1</intro_len>
<setTopic>%3Cp%3ETest%20Topic%3C%2Fp%3E</setTopic>
<essay_active>1</essay_active>
<essay_date>01-01-70</essay_date>
<essayID>29</essayID>
<topic>Test Essay Topic</topic>
<intro>Test Introduction Paragraph</intro>
<support>Test Supporting Paragraph 2nd test supporting paragraph</support>
<conclusion>Test Conclusion Paragraph</conclusion>
<essay_comment>1</essay_comment>
<submitted>1</submitted>
<dateSubmitted>07-11-16</dateSubmitted>
<essay_grade></essay_grade>
<AdStudentEssayID>59</AdStudentEssayID>'
So the question is, Why is it doing this? Why does it output 'intro','support','conclusion', and 'topic' instead of saving them to the variable?
I have a database with lots of courses in for example, breakfast_cereal, breakfast_toast, lunch_salad, lunch_main etc etc
Im using this to put the data they enter into a variable containing there results, for example:
breakfast_toast = Wholemeal;Brown;50/50;
and
breakfast_hotdrinks = Tea;Coffee;Milk;
This is the script im using to gather that information:
if(!empty($_POST['toast_selection'])) {
foreach($_POST['toast_selection'] as $toast) {
$toast = trim($toast);
if(!empty($toast)) {
$toastchoices .= "$toast;";
}
}
}
This works absolutely fine, But i have about a lot of entries to collect and if they add more to the database i want them to automatically gather.
I had a go at trying to think of a way but i just can't figure it out, This is what i tried:
All the inputs are called the same as the $course_menuname, for example breakfast_cereal[]
$query = "SELECT * FROM course";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$course_menuname = $row['course_menuname']; #E.G breakfast_cereal, breakfast_toast, lunch_main
$course_item = $row['course_jsname']; #E.G cereal, toast, jacketpotato
$postResults = $_POST[''.$course_menuname .''];
if(!empty($postResults)) {
echo $postResults."<br />";
foreach($postResults as $course_item) {
$course_item = trim($course_item);
if(!empty($course_item)) {
$course_item1 .= "$course_item;";
}
}
}
echo $course_item1."<br />";
}
This is what the end result should look for
if(!empty($_POST['toast'])) {
foreach($_POST['toast'] as $toast) {
$toast = trim($toast);
if(!empty($toast)) {
$toastchoices .= "$toast;";
}
}
}
if(!empty($_POST['toastextra_selection'])) {
#Gather Toast EXTRAs Choices
foreach($_POST['toastextra_selection'] as $toastextra) {
$toastextra = trim($toastextra);
if(!empty($toastextra)) {
$toastextrachoices .= "$toastextra;";
}
}
}
if(!empty($_POST['toastextra_selection'])) {
#Gather Cold Drinks Choices
foreach($_POST['colddrinks_selection'] as $colddrinks) {
$colddrinks = trim($colddrinks);
if(!empty($colddrinks)) {
$colddrinkschoices .= "$colddrinks;";
}
}
}
if(!empty($_POST['hotdrinks_selection'])) {
#Gather Hot Drinks Choices
foreach($_POST['hotdrinks_selection'] as $hotdrinks) {
$hotdrinks = trim($hotdrinks);
if(!empty($hotdrinks)) {
$hotdrinkschoices .= "$hotdrinks;";
}
}
}
First of all you should not use the mysql_* functions anymore. These functions are marked as deprecated. Alternativly you can use PDO or the mysqli_* functions.
I guess group change is what you need. Let 's start with a simple example.
try {
$data = array();
$pdo = new PDO(...);
foreach ($pdo->query("SELECT * FROM course") as $row) {
if (!isset($data[$row['course_menuname'])) {
$data[$row['course_menuname']] = array();
}
if (!empty($row['course_item'] && in_array($row['course_item'], $_POST[$row['course_menuname'])) {
$data[$row['course_menuname'][] = $row['course_item'];
}
}
} catch (PDOException $e) {
// error handling
}
// Output all choices by menuname
foreach ($data as $key => $value) {
echo "Choices for " . $key . "\n";
echo implode(";", $value) . "\n";
}
I don’t know how to search the net for the answer and I’m not sure how to explain the problem, so I’m sorry if it’s not clear or if it’s been asked before.
Here’s the deal: I need to show some items which have different statuses (there’s “unanswered”, “in discussion” and “answered”). What’s happening now is that the unanswered questions are being shown, the correct text is being shown for the questions that are in discussion, but the text for the question that are answered is the same as the “in discussion”. When one of the questions is moved from “unanswered” to “in discussion”, the correct text is being show for the “answered” questions. When there are no “unanswered” questions, the text is correct for that item. But the other items are getting the same text as the “unanswered” and the questions that should be shown in “in discussion” aren’t visible.
Does someone know what I can do to fix this? I'll put some code below. Thanks!!!
overzicht.php
<?php
session_start();
if(!isset($_SESSION['views']))
{
header('Location: index.php');
}
else
{
$feedback = "";
try
{
include_once('classes/question.class.php');
$oQuestion = new Question();
$oQuestionsUnanswered = $oQuestion->getQuestionsUnanswered();
$oQuestionsInDiscussion = $oQuestion->getQuestionsInDiscussion();
$oQuestionsAnswered = $oQuestion->getQuestionsAnswered();
}
catch(Exception $e)
{
$feedback = $e->getMessage();
}
}
?>
To show the different items (this is repeated twice for the other 2 statuses, with other variables e.g $oQuestionsAnswered):
<h3>Vragen onbeantwoord:</h3>
<div id="questionUnanswered">
<?php
if(isset($oQuestionsUnanswered))
{
$unanswered_details = "";
while($arr_unanswered = mysqli_fetch_array($oQuestionsUnanswered))
{
$unanswered_details .= "<div class='head'>";
$unanswered_details .= "<div class='titel'>";
$unanswered_details .= "<a href='full_topic.php?id=".$arr_unanswered['bericht_id']."'>".$arr_unanswered['bericht_titel']."</a></div>";
$unanswered_details .= "<div class='datum'>" . $arr_unanswered['bericht_datum'] . "</div></div>";
}
echo $unanswered_details;
}
else
{
echo $feedback;
}
?>
</div>
question.class.php (this is also repeated for the other 2)
public function getQuestionsUnanswered()
{
include('connection.class.php');
$sql = "SELECT *
FROM tblbericht
WHERE fk_status_id = 3;";
$result = $conn->query($sql);
if($result->num_rows!=0)
{
return $result;
}
else
{
throw new Exception("Er zijn momenteel nog geen onbeantwoorde vragen");
}
mysqli_close($conn);
}
IMO you make a big mistake, you split the query moment from the fetch moment, so you can create an array of question objects, than you use it inside the page.
Here's a draft of your code adapted:
public function getQuestionsUnanswered()
{
include('connection.class.php');
$sql = "SELECT *
FROM tblbericht
WHERE fk_status_id = 3;";
$result = $conn->query($sql);
$_rv =array()
if($result->num_rows!=0)
{
while($arr = mysqli_fetch_array($result))
{
$_rv[] = new QuestionBean($arr);
}
}
else
{
throw new Exception("Er zijn momenteel nog geen onbeantwoorde vragen");
}
mysqli_close($conn);
return $_rv
}
Then
<h3>Vragen onbeantwoord:</h3>
<div id="questionUnanswered">
<?php
if(count($oQuestionsUnanswered))
{
$unanswered_details = "";
foreach( $oQuestionsUnanswered as $bean)
{
$unanswered_details .= "<div class='head'>";
$unanswered_details .= "<div class='titel'>";
$unanswered_details .= "<a href='full_topic.php?id=".$bean->bericht_id."'>".$bean->bericht_titel."</a></div>";
$unanswered_details .= "<div class='datum'>" . $bean->bericht_datum . "</div></div>";
}
echo $unanswered_details;
}
else
{
echo $feedback;
}
?>
</div>
Of course you can optimize it using 1 class for all kind of question and 1 function using the paramiter to select wich kind of question you need.
The type of question will be a parameter of QuestionBean.
QuestionBean is a Bean :)
As bean I mean a "simple" data object where each attributes has a getter and setter OR is public.
I use the __constructor as initializer with a function called populate:
class simpleBean{
public $id;
public function __construct($params){
// some logic as need
}
// simple populate
public function populate($params){
$valid = get_class_vars ( self );
foreach($params as $k => $v){
if(!isset($valid[$k]){
// if this key has no attrib matchig I skip it
continue;
}
$this->$k = $v;
}
}
}
class QuestionBean extend simpleBean{
public $attr1;
public function __construct($params){
// may be I've some common logic in parent
parent::__construc($params);
//
$this->populate($params);
}
}
Now after the
while($arr = mysqli_fetch_array($result))
{
$_rv[] = new QuestionBean($arr);
}
you will have an array ($rv) of beans, each bean is a single result row of your query, but it's an object, that's much better than a stupid array.
I have asked a couple of questions on here in a rush, and I am getting nowhere fast, I keep changing things and just ending up with a different problem, and no closer to having a clue what is causing it. I am a PHP MYSQL man, and I am having to work with Access via the COM class.
Basically the client has multiple servers, each with an access database, and each with a CMS, the tables should contain the same data and have slipped out of Sync. It is my job to come up with a way of resyncing them.
I have came to bringing the data out into an Array, serializing it and saving it to a file on the main server (the one all should sync to) and then on the other servers, downloading the file, unserializing it and item by item, checking if it is in the DB, and if not inserting it. The insert is failing. I have tried building an sql query for each item and doing $this->conn->Execute(); and that is failing row by row on silly things, so I am now trying this:
function syncCMS()
{
$this->output['msg'] .= "<p><b>The following properties were added to the database on ." . $this->hsite . "</b></p>";
$this->get_field_names();
$this->make_connection(); //assigns connection to $this->conn
$rs = new COM('ADODB.Recordset');
$rs->CursorType = 2;
$rs->CursorLocation = 1;
$rs->LockType = 4;
$rs->Open($this->table_name,$this->conn);
foreach ($this->awayPropertyDetails as $key => $property)
{
$this->check_for_property($property['pname']);
if (!$this->property_exists || $this->mode == "fullSync")
{
unset($values);
$bfields = array("pshow","rent","best", "oda1", "oda2", "oda3", "oda4", "oda5", "oda6", "odap", "topool","tomountain","tofitness","tosauna"); //stores the yes/no values
$q = "INSERT INTO " . $this->table_name . " (" . $this->dbfields . ") VALUES (";
foreach ($property as $k => $value)
{
if ($k == "Kimlik") {
$value = null;
}
if ($k == "tarih")
{
$value = date("d/m/Y");
$value = "'" . $value . "'";
}
if (in_array($k,$bfields))
{
if ($value == "")
{
$value = 'FALSE';
}
else
{
$value = 'TRUE';
}
}
$rs->fields->$k = $value;
$this->output['msg'] .= $property['pname'] . " added";
}
$rs->BatchUpdate();
$rs->Close();
$this->conn->Close();
//$this->download_images($property['OBJECT_NR'],$k);
//$this->output['msg'] .= "<p>Images added</p>";
}
}
$message .= "</ul>";
$this->output['msg'] .= $message;
$this->sendOutput();
//print_r($property);*/
}
And getting this:
Fatal error: Uncaught exception 'com_exception' with message 'Unable to lookup `Kimlik': Unknown name. ' in D:\inetpub...
Kimlik is the name of the first field, the Auto Number field, I took it out and the problem shifted to the second field.
I got there with:
$sql = "SELECT * FROM " . $this->table_name;
if (!$this->property_exists || $this->mode == "fullSync")
{
$this->make_connection();
$rs->Open($sql,$this->conn);
$rs->addnew();
foreach($rs->Fields as $field)
{
if ($field->name != "Kimlik")
{
$rs->Fields[$field->name] = $property[$field->name];
}
}
$rs->Update();
$rs->Close();
$this->conn->Close();
$msg = $this->download_images($property['OBJECT_NR'],$k);
$this->output['msg'] .= $property['pname'] . " added<br/>" . $msg . "<br/><br/>";
}