How to remove br while extracting contents from database? - php

I'm trying to develop the dynamic site using PHP and obsolete mysql_query.
I need to extract limited contents from my database so I've used substr and this content is placed at the index page. But while the user edits the page, the content is formatted, sometimes the font size is too large, sometimes the content has lots of <br>. It destroys the look of my website. I'm troubled by unnecessary <br> and want to remove it and also want to ignore the formatted font size in the index page.
My code goes like this:
<?php
$sql = "SELECT contents FROM table";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$contents = $row['contents'];
echo substr($fld_page_details, 0,125);
}
?>

Try the following:
<?php
$sql = "SELECT contents FROM table";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$contents = $row['contents'];
echo str_replace('<br>', '', $contents);
}
?>

Related

Styling output of database from php loop

I'm trying to display data from database and it is important to me that this output is placed on different sides of website. I used php to connect to database, and ajax jquery to refresh data because every 20second values change.
I tried to
echo <div styles='position: absolute; top: 0px' class='text'>{$row['id']}</div>
in a foreach loop but when I do this all 6 of my id's are stacked on top each other.
Making <div> outside loop was unsuccessful too. I guess my problem is in reading data from database because I read all at once but I don't know any other way to do this except wrtiting 6 connection files to gather only the one value that I want to display and then styling it, but I feel like there is smarter way of doing this.
This is my code. Just want to say this is my first contact with php.
<?php
$hostname = "someinfo";
$username = "someinfo";
$password = "someinfo";
$db = "someinfo";
$dbconnect = mysqli_connect($hostname,$username, $password,$db) or die("cant");
if ($dbconnect->connect_error) {
die("Database connection failed: " . $dbconnect->connect_error);
}
$sensor_names = array();
$query2 = mysqli_query($dbconnect,"show tables");
while($row2 = mysqli_fetch_array($query2)){
if($row2[0] == 'sensors' or $row2[0] == 'measurments'){
break;
}
else{
array_push($sensor_names,$row2[0]);
}
}
$query = mysqli_query($dbconnect, "select s.id, s.sensor_name, max(dev.id), dev.temprature, dev.date from sensors s, `{$sensor_names[0]}` dev where s.id=dev.sensor_id gro
up by s.id, s.sensor_name order by s.id asc");
while($row = mysqli_fetch_array($query)){ //i konw this is ugly but this is working placeholder
foreach($sensor_names as $sn){
$query = mysqli_query($dbconnect, "select s.id, s.sensor_name, dev.temprature, dev.date from sensors s, `{$sn}` dev where s.id=dev.sensor_id order by dev.id desc limit 1");
$row = mysqli_fetch_array($query);
echo "
{$row['id']}
{$row['sensor_name']}
{$row['temprature']}
{$row['date']}
<br>";
}
}
?>
This is off-the-cuff from a guy who hasn't touched PHP in a long while, so watch for major bugs. But the basic idea is like this: build the code in a variable, and when done, echo out the entire variable. Makes it easier to add the structure/formatting you want. Note that you can also stick in a style tag along with that code and blurp out the style along with the "table" (Personally, I wouldn't use a table for styling, this is just for demo).
Note: I didn't style the output so that it puts the data on either side of the page - I left that for you to do. It's basic HTML - divs, styles, maybe css grid or flexbox. The point is to create your CSS/HTML/PHP mashup in a string variable and output the entire thing when done.
$out = '<style>.cell_id{font-weight:bold;}</style>';
$out .= '<table><tr><th>Label 1</th><th>Label 2</th><th>Etc</th></tr>'; //<=== ADDED!
while($row = mysqli_fetch_array($query)){
foreach($sensor_names as $sn){
$query = mysqli_query($dbconnect, etc. etc. etc.);
$row = mysqli_fetch_array($query);
$out .= "
<tr>
<td class='cell_id'>{$row['id']}</td>
<td>{$row['sensor_name']}</td>
<td>{$row['temprature']}</td>
<td>{$row['date']}</td>
</tr>";
}
}
echo $out;
Ok I think I got it. Cssyphus's answer got me thinking and I wrote something like that array_push($data, $row) and $data is two dimentional array that hold all data I need and now I can style it easily.

How do I display several images using URLs saved in phpmyAdmin in a website?

See Table of report data
The table is as displayed in the image above. I wanted to display all the data including several images for which URLs are saved in the imageURL column separated with a semicolon.
The number of image URLs differs in each columns.
The URLs refer to image path in upload folder as shown below:
InvestigatorsReportApi/uploads/KBC589L-1.jpg;
InvestigatorsReportApi/uploads/KBC589L-2.jpg;
InvestigatorsReportApi/uploads/KBC 589L-3.jpg;
How would I display this in a website?
You should simmply make a query about the URL:
$sql = "SELECT url FROM table";
$result = $conn->query($sql);
After that echo it into the <img> tag src attribute:
while($row = $result->fetch_assoc()) {
echo "<img src='".$row["url"]."'>";
}
And there you have it. The sample code above will print every image in the database.
Just try this
$sql = "SELECT url FROM table";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
foreach(explode(';',$row["url"]) as $image) {
echo "<img src='".$image."'>";
}
}
First fix your table. It is bad. You should let the attributes occupy the first row:
id: name: LOA: regNO: rout..., then
first you need to use explode function for separate your image url
$image=explode(";",$imageURL);
then use foreach loop for display image
foreach($image as $value)
{
<img src='".$value."'/>
}

PHP output as link from database

I have the following code that works by outputting as a link ( the link comes from a field in my database) I wish to do the same for the code below, however i cannot get it work, here is the example of what I have that works, and the code that i wish to make output as a link:
Working Code what I want it to look like
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM adrenaline WHERE title LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo '<br> '. $row['title'] .'';
}
}
?>
And the code that i have at the moment, it works by be manually typing in the hyper link, however I wish to make it take the link from the database like the example above
//query the database
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
//ferch the results / convert results into an array
WHILE($rows = mysql_fetch_array($query)):
$title = $rows['title'];
echo "<a href='shard.php'>$title</a>";
endwhile;
?>
Many thanks!
I am not 100% certain if this is what you meant to ask... let me know in comments:
<?PHP
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
if(mysql_num_rows($query) >= 1) {
while($rows = mysql_fetch_array($query)) {
echo sprintf("%s", $rows["description"], $rows["title"]);
}
} else { echo "No hobbies found."; }
?>
I believe you might have faced some syntax issues while dealing with quotes parsing a variable in <a html tag. Consider using sprintf something like in my example.
I have also added a mysql_num_rows() just in case and you can see its a good fail-safe method incase there are no rews found on any select query.
IMPORTANT: STOP using mysql_ functions because its deprecated from new PHP versions. Use PDO or mysqli instead.

How to select certain fields from table in mySQL using PHP

I'm trying out my hand at php at the moment - I'm very new to it!
I was wondering how you would go about selecting all items from a mySQL table (Using a SELECT * FROM .... query) to put all data into an array but then not displaying the data in a table form. Instead, using the extracted data in different areas of a web page.
For example:
I would like the name, DOB and favorite fruit to appear in one area where there is already say 'SAINSBURYS' section hardcoded into the page. Then further down the next row that is applicable to 'ASDA' to appear below that.
I searched both here and google and cant seem to find an answer to my strange questions! Would this involve running the query multiple times filtering out the sainsburies data and the asda data where ever I wanted to place the relevant
echo $row['name']." ";
echo $row['DOB']." "; etc etc
next to where it should go?
I have got php to include data into an array (I think?!)
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
echo $row['name']." ";
echo $row['DOB']." ";
echo $row['Fruit']." ";
}
?>
Just place this (or whatever your trying to display):
echo $row['name']." ";
Anywhere you want the info to appear. You can place it within HTML if you want, just open new php tags.
<h1>This is a the name <?php echo $row['name']." ";?></h1>
If you want to access your data later outside the while-loop, you have to store it elsewhere.
You could for example create a class + array and store the data in there.
class User {
public $name, $DOB, $Fruit;
}
$users = new array();
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$user = new User;
$user->name = $row["name"];
$user->DOB = $row["DOB"];
$user->Fruit = $row["Fruit"];
$users[$row["name"]] = $user;
}
Now you can access the user-data this way:
$users["USERNAME"]->name
$users["USERNAME"]->DOB
$users["USERNAME"]->Fruit

Inserting text from textarea into MySQL database without losing formatting

I am trying to add text from a textarea on my site into a MySQL database.
Below is the PHP code that is adding the text to the database.
if (isset($_POST['text']))
{
$text = sanitizeString($_POST['text']);
$text = preg_replace('/\s\s+/', ' ', $text);
$query = "SELECT * FROM profiles WHERE user='$user'";
if (mysql_num_rows(queryMysql($query)))
{
queryMysql("UPDATE profiles SET text='$text' where user='$user'");
}
else
{
$query = "INSERT INTO profiles VALUES('$user', '$text')";
queryMysql($query);
}
}
else
{
$query = "SELECT * FROM profiles WHERE user='$user'";
$result = queryMysql($query);
if (mysql_num_rows($result))
{
$row = mysql_fetch_row($result);
$text = stripslashes($row[1]);
}
else $text = "";
}
$text = stripslashes(preg_replace('/\s\s+/', ' ', $text));
And below is the code of the form.
<textarea name='text' cols='40' rows='3'>$text</textarea><br />
But when the data is inputted, it shows it in the database correct but not showing it displayed properly. See the images below:
The text that is entered
How the text is displayed on the page
How the text is in the database
This is the PHP code that displays the text on the page.
$result = queryMysql("SELECT * FROM profiles WHERE user='$user'");
if (mysql_num_rows($result))
{
$row = mysql_fetch_row($result);
echo stripslashes($row[1]) . "<br clear=left /><br />
Hope you can help!!
EDIT: added extra php code
Your text, unless you're using a rich-text editor, such as Mark-down (as here on Stackoverflow), is styled by your CSS, not by the contents of the textarea itself.
If the problem is preservation of new-lines, then you could run the string through the nl2br($text) function before storing in, or retrieving from, the database.
I'd suggest on retrieval would be better, but that's just my opinion (and I can't offer any evidence to back it up).
Or you can use
echo nl2br($test);

Categories