Below is the index page: having these code: Data gets populated in a div as expected.
<h2>Search for users</h2>
<input type="text" name="search" id="search" autocomplete="off" placeholder="Enter Customer ID here....">
<div id="output"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#search").keyup(function(){
var query = $(this).val();
if (query != "") {
$.ajax({
url: 'ajax-db-search.php',
method: 'POST',
data: {query:query},
success: function(data){
$('#output').html(data);
$('#output').css('display', 'block');
$("#search").focusin(function(){
$('#output').css('display', 'block');
});
}
});
} else {
$('#output').css('display', 'none');
}
});
});
</script>
This is the ajax-db-search.php page. (In the IF tags I tried it with == and no good luck yet.)
<?php
$conn=mysqli_connect("*****","*********","******","*****");
$query = "SELECT * FROM `create_customer` WHERE `Customer Id` LIKE '{$_POST['query']}%' LIMIT 6";
$result = mysqli_query($conn, $query);
$plan = $query['Plan'];
if ($plan = "planA") {
while ($user = mysqli_fetch_array($result)) {
echo "<h2>".$user['Customer Name']."</h2>";
echo "<h4><a href='http://smjw.phatake.in/admin/cc.php?recordID=".$user['id']."'>Update Profile Details</a></h4>";
echo "<h4><a href='http://smjw.phatake.in/admin/planA_details.php?recordID=".$user['Customer Id']."'>Receive Payment</a></h4>";
var_dump ($plan);
}
}
if ($plan = "planB") {
while ($user = mysqli_fetch_array($result)) {
echo "<h2>".$user['Customer Name']."</h2>";
echo "<h4><a href='http://smjw.phatake.in/admin/cc.php?recordID=".$user['id']."'>Update Profile Details</a></h4>";
echo "<h4><a href='http://smjw.phatake.in/admin/planB_details.php?recordID=".$user['Customer Id']."'>Receive Payment</a></h4>";
}
}
if ($plan = "planC") {
while ($user = mysqli_fetch_array($result)) {
echo "<h2>".$user['Customer Name']."</h2>";
echo "<h4><a href='http://smjw.phatake.in/admin/cc.php?recordID=".$user['id']."'>Update Profile Details</a></h4>";
echo "<h4><a href='http://smjw.phatake.in/admin/planC_details.php?recordID=".$user['Customer Id']."'>Receive Payment</a></h4>";
}
}
if ($plan = "planA1") {
while ($user = mysqli_fetch_array($result)) {
echo "<h2>".$user['Customer Name']."</h2>";
echo "<h4><a href='http://smjw.phatake.in/admin/cc.php?recordID=".$user['id']."'>Update Profile Details</a></h4>";
echo "<h4><a href='http://smjw.phatake.in/admin/planA1_details.php?recordID=".$user['Customer Id']."'>Receive Payment</a></h4>";
}
}
else {
echo "<p style='color:red'>User not found...</p>";
}
?>
The Problem is with the If condition: The Url's that needs to be displayed on my index page should change according to the $plan variable. But for some reason the $plan variable is always planA..
There are 4/5 Plans.. planA, planB, planc, planA1 each having different Urls that needs to displayed.
The URL do get populated but will be always the First IF conditions URL for all the customers.
Please help me out with this. Stuck for big time.
-------Update-------------
I want each of the Receive Payment to be according to the if conditions.. Now its all only planA
Here i am using php pdo for perform the search task.
i am create a two file 'search.php' is a send ajax request to query.php file.
search.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search</title>
<!-- jQuery cdn link -->
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
</head>
<body>
<input type="text" id="search" placeholder="Search">
<div class="table-div" style="display: none"></div>
</body>
</html>
<script>
$(document).ready(function(){
$("#search").keyup(function(){
$.get("/query.php", {data:$(this).val()}, function(data, status){
let row = JSON.parse(data);
let table = "";
table += "<table>";
table += "<thead>";
table += "<tr>";
table += "<th>Customer name</th><th>Customer salary</th>";
table += "</tr>";
table += "</thead>";
table += "<tbody>";
if(row.data != "No data found") {
$.each(row.data, function(key, value){
table += "<tr>";
table += "<td>"+ value.customer_name +"</td>";
table += "<td>"+ value.cust_sal +"</td>";
table += "</tr>";
});
}
table += "</tbody>";
table += "</table>";
$(".table-div").html(table);
$(".table-div").show();
});
});
});
</script>
query.php
<?php
// This is a database connectivity
$conn = new PDO("mysql:host=localhost; dbname=test;", 'root', '');
if(isset($_GET['data']))
{
$query = "%".$_GET['data']."%";
$searchSQL = "SELECT * FROM cust WHERE customer_name LIKE :cname";
$searchState = $conn->prepare($searchSQL);
$searchState->bindParam(":cname", $query);
if($searchState->execute())
{
if($searchState->rowCount() > 0)
{
$data = $searchState->fetchAll();
}
else
{
$data = "No data found";
}
}
echo json_encode(["data" => $data]);
}
?>
Hmm you said you tried == it should be == and not =.
Firstly please note your sql queries any kind of query should be prepare statements even if you trust your users.
Now please note that:
echo "planA"=="plana" ? "yes" : "no"; // Output no. Have you tried this?
Edit: I overlooked " But for some reason the $plan variable is always planA.." that is because of = in your ifs
$plan = "";
if ($plan = "a") {
echo $plan;
}
if ($plan = "b") {
echo $plan;
}
if ($plan = "c") {
echo $plan;
}
//output: abc
Lastly, please use else if, you don't need to check if 3 times it can only be 1 option.
Edit 2: I think you have some way to go. Please have look at the code below.
Here is the complete working with your bug I think:
<?php
// Since I have no post i will set it by default
$_POST['query'] = 'AZ12';
// Check for data validation...
if (!isset($_POST['query']) || empty($_POST['query'])) return;
// Now for query
$query = "SELECT * FROM `create_customer` WHERE `Customer Id` LIKE ? LIMIT 6";
// Prepare the statement to insert user_answer in ? above
// replace "s" based on your appropriate var type
$stmt = $conn->prepare($query);
// $stmt->bind_param("s", "%".$_POST['query']."%"); <-- This would yield error
// ^ fix: Store the 2nd param first
$like = "%{$_POST['query']}%";
$stmt->bind_param("s", $like);
$stmt->execute();
// Get the results
$result = $stmt->get_result();
echo "<br/>";
print_r($result);
// Output: mysqli_result Object ( [current_field] => 0 [field_count] => 3 [lengths] => [num_rows] => 1 [type] => 0 )
// ^ This will show all the elements part of $result (your case 6)
// Why this? Because to me it seems like you have hard-coded plans
// because if $plan = A,B,C and then you insert while loop inside the if's
$plans = array(0 => 'PlanA', 1 => 'PlanB', 2 => 'PlanC');
foreach($plans as $value) {
echo "<h1>$value</h1><br/>";
// Now loop as assoc like you have...
while ($row = $result->fetch_assoc()) {
print_r($row);
// ^ With above get the data value you need such as:
// echo "<h2>".$row['Customer Id']."</h2>";
}
// Add this to fix the fetch_assoc
$result->data_seek(0); // without this you will see the image below
}
// ^ Output Notice we only show plan A rows!!! look image below.
// Fix indicate by $result->data_seek(0);
?>
I am assuming this is what you get: "Why only A show?"
Related
I am looking for some initial direction on this one because I cannot seem to find my way with it. Let me explain... I'm creating a music website and having a search bar. It filters information as the user types. I don't want to make a separate .php file for each song on the website. (Eg: song1.php, song2.php, etc...). There should be one PHP template file, that outputs the webpage for ALL songs. With my code, when I try searching with the search bar, it opens the template file as expected but it fills the file with information of only the first row from the mysql table. This is the form, its in the index page:
<script type = "text/javascript "src = "jquery.js">
<form class="navbar-form navbar-left" >
<div class="form-group">
<input type="text" class="form-control" id="search" placeholder="Search for songs, artists" autocomplete="off">
<div id = "searchresults"> </div>
Then there's the search.js file having two tasks, that is to check if a result has been clicked and also if the user has pressed a key. Its like this:
$('#search').keyup(function()
{
var searchterm = $ ('#search').val();
if (searchterm != '')
{
$.post('search.php', {searchterm:searchterm},
function(data)
{
$('#searchresults').html(data);
});
}
else{
$('#searchresults').html('');
}
});
$('#mylink').click(function(){
var wanted = $('#mylink').val();
$.post('/web/ztemplate.php', {wanted:wanted});
});
I think it's the one having an error but I can't figure out where it is. The template file has this php code :
$search = $_POST['wanted'];
$find = mysql_query("SELECT * FROM search WHERE title LIKE '%$search%'");
$row = mysql_fetch_assoc($find); $title = $row["title"];
There's a search.php file which queries the database to provide information for the instant search. It looks like this :
$search = mysql_real_escape_string(trim($_POST['searchterm']));
if ($search == '' && ' '){
echo 'No results found';
}
else {
$find_videos = mysql_query("SELECT * FROM search WHERE keywords LIKE '%$search%'");
$count = mysql_num_rows($find_videos);
if ($count ==0){
echo 'No Results found for '.$search;
}
else {
while($row = mysql_fetch_assoc($find_videos)){
$title = $row["title"];
$link = $row["link"];
echo "<a href = '$link'><h5 id = 'mylink'> $title <h5> </a> <hr /> ";
}
}
}
Any help is much appreciated.
why you not send an AJAX??
$('#search').keyup(function(){
var searchterm = $ ('#search').val();
if (searchterm != ''){
$.ajax({
type: 'POST',
data: {
"searchterm": searchterm,
"_token":"{{ csrf_token() }}"
},
url: "{{URL::asset('yourPHP')}}",
success: function(response){
$('#searchresults').html(response);
}
});
}else{
$('#searchresults').html('');
}
});
PHP
function searchSong($search =''){
$search = (trim($_POST['searchterm']));
$out='';
if ($search == '' && ' '){
echo 'No results found';
}else {
$sql = "SELECT * FROM search WHERE title LIKE '%$search%'";
$data= DB::select($sql);
$count = count($data);
if ($count ==0){
echo 'No Results found for '.$search;
}else {
foreach ($data as $key => $row) {
$title = $row["title"];
$link = $row["link"];
$out .= "<a href = '$link'><h5 id = 'mylink'> $title </h5> </a> <hr /> ";
}
}
}
return $out;
}
I have jQuery ListView that loads data from a php file. I also have a checkbox that onclick should be able to filter the list. The filtering is done by sending a post message to server and refreshing the list. However, the checkbox list is not filtering the list. The code below is only part of the whole implementation. Here is the page:
http://i.cs.hku.hk/~hsbashir/Project_Work/Listview/restaurant_list.html
This is the HTML implementation:
<head>
<script>
lastRecord=0;
function loadRest(){
$('#sample').html( 'hello' );
$.get(
"queryRestaurantsList.php?lastRecord="+lastRecord,
function( data ) {
$('#rest_mesgs').append( data )
.listview( 'refresh' );
}
);
}
</script>
</head>
<body onload="loadRest()">
<div data-demo-html="true">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Select your type of Restaurant:</legend>
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a" onchange="onfilter()" value="Vegetarian"/>
<label for="checkbox-h-2a">Vegetarian</label>
</fieldset>
</form>
</div>
<div data-demo-html="true">
<ul data-role="listview" data-theme="a" data-split-theme="b" data-split-icon="plus" data-inset="true" id="rest_mesgs">
<li data-role="list-divider">Restaurants</li>
</ul>
</div>
<script>
function onfilter(){
if($("#checkbox-h-2a").prop('checked')){
document.getElementById("hehe").innerHTML = "if condition is true";
var a = document.getElementById("checkbox-h-2a");
$.post("queryRestaurantsList.php",
{
filter0 : a.value;
},
function(data){
$('#rest_mesgs').append( data )
.listview( 'refresh' );
});
}
else {
document.getElementById("hehe").innerHTML = "not working";
}
}
</script>
</body>
This is php file:
mysql_connect($host,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
//Check if POST array is empty or not
if ($_POST == null){
$query = "SELECT Name,Short_Loc,Image_Link,Type FROM Restaurant_Info";
$result = mysql_query($query) or die( "Unable to execute query");
while ($row = mysql_fetch_array($result)){
print '<li>';
print '<a href="'.$row['Full_Link'].'">';
print '<img style="height:80px;" src="'.$row['Image_Link'].'">';
print '<h2 style="text-wrap : normal">'.$row['Name'].'</h2>';
print '<p id="type" class="ui-li-aside"><strong>'.$row['Type'].'</strong></p>';
print '<p>'.$row['Short_Loc'].'</p>';
print '</a>';
print '</li>';
}
}
else {
$value1 = $_POST[filter0];
$query0 = 'SELECT Name,Short_Loc,Image_Link FROM Restaurant_Info WHERE Type LIKE ';
$query0 = $query0.'"%'.$value1.'%"';
$result = mysql_query($query0) or die( "Unable to execute query");
$num_results = mysql_num_rows($result);
if ($num_results == 0){
print "Your criteria does not match any of the restaurants";
}
else{
while($row = mysql_fetch_array($result)) {
print '<li>';
print '<a href="'.$row['Full_Link'].'">';
print '<img style="height:80px;" src="'.$row['Image_Link'].'">';
print '<h2 style="text-wrap : normal">'.$row['Name'].'</h2>';
print '<p>'.$row['Short_Loc'].'</p>';
print '</a>';
print '</li>';
}
}
I can see 2 errors, but unfortunately I can't test them.
1 - This php part:
else {
$value1 = $_POST[filter0];
Should be replace with:
else {
$value1 = $_POST['filter0'];
Otherwise filter0 will be treated as a constant instead of a string.
2 - On your html, you did:
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a" onchange="onfilter()" value="Vegetarian"/>
This should be
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a" onclick="onfilter()" value="Vegetarian"/>
I think a checkbox won't fire onchange when you check or uncheck it.
1 . To maintain checkbox state change use jQuery.toggle(). It's the safest way.
$("#checkbox-h-2a").toggle(function(){
var filter = $(this).val();
getListviewItems({filter0: filter});
}, function() {
getListviewItems();
});
2 . Make one function with params for getting list items. That way you'll keep your code clean and easy to maintain.
function getListviewItems(opt) {
opt.filter0 = (opt.filter0 == undefined)?'':opt.filter0;
/* Body of function, post and/or get calls, etc. */
}
I have a new question about a project I had been working on. I was designing a grid with different colored cells. it has a hidden div which shows when a cell is clicked, however I realized that only one cell(the last one of it's type) will show. i.e. if I have 2 objects with the column "objaffinity" as 0 ("enemy") it will show both red cells on the grid, however only the last one will actually work.
how can I make it so that it will show the proper information for each cell?
here's my code:
mapgen.php:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="cellinfo.js"></script>
<script src="cmenu.js"></script>
<?php
require("sql.php");
$sql = <<<SQL
SELECT *
FROM `maps`
WHERE `objpresent` = 1
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
} // ran the query
//$xobj = array();
//$yobj = array();
$otype = array();
$oname = array();
$xyobj = array();
while($row = $result->fetch_assoc()){
$xyobj[$row['x']][$row['y']] = true;
$otype[$row['id']]=$row['objaffinity'];
$oname[$row['id']]=$row['object'];
}
// get the rows
$cellid=1;
//find whether the row is obstructed
for ($y = 0; $y < 20; $y++) {
echo '<tr>';
for ($x = 0; $x < 25; $x++) {
echo "<td>";
//Detect what type of object it is
if (isset($xyobj[$x][$y])) {
if($otype[$cellid] == 2)
{
echo "<a href='#'> <div class='foe'> </div><div class='foepopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
elseif($otype[$cellid] == 1)
{
echo "<a href='#'><div class='friend'></div><div class='friendpopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
else
{
echo "<a href='#'> <div class='neutral'></div><div class='neutralpopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
$cellid++;
}
echo '</td>';
}
echo '</tr>';
}
?>
Cellinfo.js:
$(document).ready(function(){
//initially hide all popups
$(".foepopup").hide();
$(".neutralpopup").hide();
$(".friendpopup").hide();
//foebutton selected
$(".foe").on("click",function(e){
$(".friendpopup").hide();
$(".neutralpopup").hide();
$(".foepopup").show();
});
//close foe when selected
$(".foepopup").on("click",function(e){
$(".foepopup").hide();
});
//neutral button pressed
$(".neutral").on("click",function(e){
$(".foepopup").hide();
$(".friendpopup").hide();
$(".neutralpopup").show();
});
//close neutral
$(".neutralpopup").on("click",function(e){
$(".neutralpopup").hide();
});
//friend button pressed
$(".friend").on("click",function(e){
$(".foepopup").hide();
$(".neutralpopup").hide();
$(".friendpopup").show();
});
//close friend
$(".friendpopup").on("click",function(e){
$(".friendpopup").hide();
});
});
In your functions you use selectors, so for the script it does not matter which div was clicked.
Let me show you some examples:
$(".foepopup").on("click",function(e){
$(".foepopup").hide();
});
It should be something like this rather:
$(".foepopup").on("click",function(e){
$(this).hide();
});
And another example:
$(".neutral").on("click",function(e){
$(".foepopup").hide();
$(".friendpopup").hide();
$(".neutralpopup").show();
});
Rewrite it like this:
$(".neutral").on("click",function(e){
var td_tag = $(this).parent().parent();
td_tag.children(".foepopup").hide();
td_tag.children(".friendpopup").hide();
td_tag.children(".neutralpopup").show();
});
Rewrite other code on your own. this is the element on which click was triggered. td_tag will contain parent cell of a div clicked. After that, children method will allow you to find needed elements already inside specific cell.
Good luck!
I am struggling with the following PHP and JavaScript codes to have 2 sets of check-boxes filtering a range of data obtained from a MySQL database.
Here is the code:
<script type="text/javascript">
//http://jsbin.com/ujuse/1/edit
$(function() {
$("input[type='checkbox']").on('change', function() {
var boxes = [];
// You could save a little time and space by doing this:
var name = this.name;
// critical change on next line
$("input[type='checkbox'][name='"+this.name+"']:checked").each(function() {
boxes.push(this.value);
});
if (boxes.length) {
$(".loadingItems").fadeIn(300);
// Change the name here as well
$(".indexMain").load('indexMain.php?'+this.name+'=' + boxes.join("+"),
function() {
$(".indexMain").fadeIn('slow');
$(".loadingItems").fadeOut(300);
});
} else {
$(".loadingItems").fadeIn(300);
$(".indexMain").load('indexMain.php', function() {
$(".indexMain").fadeIn('slow');
$(".loadingItems").fadeOut(300);
});
}
});
});
</script>
<?php
function echoCheckboxSet($header, $divClass, $columnName, $setName) {
include ("connection.php");
$checkboxes = $con -> prepare("SELECT DISTINCT $columnName FROM item_descr ORDER BY $columnName ASC");
$checkboxes->execute();
?>
<div class="bgFilterTitles">
<h1 class="filterTitles"><?php echo $header;?></h1>
</div>
<div class="<?php echo $divClass; ?>">
<?php
while ($box = $checkboxes->fetch(PDO::FETCH_ASSOC)):
$boxColumnName = str_replace('_',' ',$box[$columnName]);
?>
<input type='checkbox' class='regularCheckbox' name='<?php echo $setName; ?>' value='<?php echo $box[$columnName]; ?>' />
<font class='similarItemsText'><?php echo $boxColumnName; ?></font>
<br />
<?php
endwhile;
?>
</div>
<?php
} // end of echoCheckboxSet
// Call our method twice, once for colors and once for prices
echoCheckBoxSet("COLOR", "colors", "color_base1", "color[]");
echoCheckBoxSet("PRICE", "prices", "price", "price[]");
?>
Then I am perfectly getting my check-boxes but when clicking on any of them they don't do anything.
My indexMain.php retrieves the values like this:
$colors = $_GET['color[]'];
echo "TEST".$colors[1];
$colors = explode(' ', $colors);
$parameters = join(', ', array_fill(0, count($colors), '?'));
$items = $con -> prepare("SELECT * FROM item_descr WHERE color_base1 IN ({$parameters})");
$items ->execute($colors);
$count = $items -> rowCount();
----------------- Adding the echo:
echo "<div>Showing ".$count."items</div>";
while($info = $items->fetch(PDO::FETCH_ASSOC))
{
echo "<div name='item' id='".$info['color_base1']."' class='itemBox'><div class='showItem'><a href='items_descr.php?itemId=".$info[id_item]."'><img class='itemImage' alt='' src='images/$info[imageMid].jpg'></img></div><br />";
echo "<div class='indexItemText'><font class='similarItemsText'><a href='items_descr.php?itemId=".$info[id_item]."'>".$info[name]."</a><font class='price'> - $".$info[price]."</div></div>";
$row_count++;
if ($row_count % 2 == 0)
{
echo "<br />"; // close the row if we're on an even record
}
}
Any idea of what could be going on?
The problem is when you build the query in your JS function:
'indexMain.php?'+this.name+'=' + boxes.join("+")
This sends color[]=Brown+Grey instead of color[]=Brown&color[]=Grey. A correct (but dirty) way to this is:
'indexMain.php?'+this.name+'=' + boxes.join('&' + this.name + '=')
You could try to use jQuery.param() ( http://api.jquery.com/jQuery.param/ ) to get a nicer code.
Also, in PHP, the checkbox values are available in the array $_GET['color'] (not $_GET['color[]']).
Edit: Sorry, read too quickly.
Answer: As you expect everywhere to use strings, use color instead of color[] in your JS and PHP code.
Ok, I am using a PHP editing form (previous person built) that submits data into an MSSQL database this works fine however when the information is submitted into the database and later retrieved the the form page (for editing) there is a <br> at the beginning of the text. If the fields start with a <ul> that <br> is not inserted. I have been trying to figure out how to stop this. One thing I tried ends up removing all <br> in the text which makes the formatting disappear, How can I keep it from inserting the <br> at the top but keeping the <br> everywhere else? here is the code I have: ( I am giving you everything up to the first field where I have the issue appear)
function fromhtml ($x) {
$x = preg_replace("/<p>/i","\n\n",$x);
//$x = preg_replace("/<br>/i","\n",$x);
$x = preg_replace("/<li>/i","\n<li>",$x);
return $x;
}
$PHP_SELF = $_SERVER['PHP_SELF'];
$course_id = #$_GET["course"];
if ($course_id == "") {
$sqlquery = "SELECT id, title, goals, outline, reference, deliverymode, updated2 = CONVERT(VARCHAR(19), updated, 120)
FROM courses WHERE division_id = '$division_id' ORDER by id";
$result = mssql_query($sqlquery);
$number = mssql_num_rows($result);
print "<table border=1 id=\"content_table\"><tr><th>ID</th><th>Title</th><th>Status</th><th>Last modified</th></tr>\n";
$i = 0;
while ($number > $i) {
$course_id = mssql_result($result,$i,"id");
$reference = mssql_result($result,$i,"reference");
$updated = mssql_result($result,$i,"updated2");
print "<tr><td>";
if ($reference == "") {
print "<a href=$PHP_SELF?division=$division_id&course=$course_id>$course_id</a>";
} else {
print "$course_id";
}
print "</td><td>";
print mssql_result($result,$i,"title");
print "</td><td>";
if ($reference == "") {
if ( (mssql_result($result,$i,"goals")=="") and (mssql_result($result,$i,"outline")=="") ) {
print "<b>No syllabus, or incomplete</b></td>";
}
} else {
print "Based on $reference";
}
print "</td><td>$updated</td>\n";
print "</tr>\n";
$i++;
}
print "</table>";
exit;
}
$sqlquery = "SELECT * FROM courses WHERE id = '$course_id'";
$result = mssql_query($sqlquery);
$number = mssql_num_rows($result);
if ($number == 0) {
print "<html><body>";
print "No course with the ID \"$course_id\" exists in the course database.";
print "</body></html>";
exit;
}
$i = 0;
$description = fromhtml(mssql_result($result,$i,"description"));
print "<html><head><title>DACC Course Syllabus - $course_id</title>";
print "<script language=\"JavaScript\" type=\"text/javascript\" src=\"/rte/richtext2.js\"></script>";
?>
<script language="JavaScript" type="text/javascript">
<!--
initRTE("/rte/images/", "/rte/", "");
//-->
function submitForm() {
updateRTEs();
document.edit-course.submit();
return false;
}
</script>
<?php
print "</head><body>\n";
//Begin Form
print "<form name=\"edit-course\" id=\"edit-form\" method=\"post\" action=\"write.php?course=$course_id\" onSubmit=\"return submitForm()\">\n";
print "<fieldset>";
print "<label for=\"description\">Course Description</label>";
$description=addslashes(preg_replace('`[\r\n]`','',$description));
?>
<script language="JavaScript" type="text/javascript">
<!--
writeRichText('description', '<?php print $description; ?>', 200, 300, true, false);
//-->
</script>
<?php
print "</fieldset>";
It that BR is at very very beginning of string then use this
$x = preg_replace("/^<br(\/|)>/i","\n",$x);
instead of that commented line
preg_replace has a fourth parameter, $limit. Setting this to 1 would limit the preg_replace to the first occurence. Alternatively you could use the regular expression ^<br>. This would only replace <br> when it is at the beginning of the string.
Edit: Sorry, I misunderstood your problem. Use $variable=preg_replace("/^<br>/i", "", $variable); to strip the first <br>.