I have managed to put this code together.
$sql = "
SELECT
inbox.ReceivingDateTime,
namnlista.namn AS SenderNumber, inbox.Text
FROM
inbox
INNER JOIN
namnlista
ON
inbox.SenderNumber = namnlista.SenderNumber";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo
$row["ReceivingDateTime"],
$row["SenderNumber"],
$row["Text"],"<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
and it shows my info fine on my page but of course like this
ReceivingDateTimeSenderNumberText
And I want to make it look like this (using my index.css file)
ReceivingDateTime SenderNumber Text
I've tried adding stuff into the echo line but every time I do my page stops working so I am doing something wrong...
I've managed to add this, and make a table I guess?
echo
"<table> <tr> <td>"
.$row["ReceivingDateTime"]."</td>".
"<td>". $row["SenderNumber"]."</td>".
"<td>".$row["Text"]."</td></tr></table>";
But still it doesnt look good, I can use padding in CSS but what should I use to make the 3 columns all start at selected points?
Now the next column starts after the same amount of empty space regardless of the length of the previous column and that is not good.
Only concatenate a space (o whatever) after echo. See this example. Concatenation of strings in PHP are with dot.
$sql = "
SELECT
inbox.ReceivingDateTime,
namnlista.namn AS SenderNumber, inbox.Text
FROM
inbox
INNER JOIN
namnlista
ON
inbox.SenderNumber = namnlista.SenderNumber";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo
$row["ReceivingDateTime"]." ", //here
$row["SenderNumber"]." ",// and here
$row["Text"],"<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
The absolute simplest way to get your data into columns would be to use
echo "<pre>" . $row["ReceivingDateTime"] . "\t" . $row["SenderNumber"] . "\t" . $row["Text"] . "</pre><br>";
This doesn't give you much structure in the html. Semantically a table is probably more appropriate but this is quick and dirty.
The <pre> tag in html means preserve whitespace, and the \t is a special character representing a tab.
Right, similar to what Christian said, you can concatenate a space after each term. But the question indicated that you wanted columns. If that's the case, you can also user '\t' for a tabbed effect.
Related
So I'm working on a stock quotes page, and in the "Find Symbol page", the user enters the symbol for a company and any symbols stored in the database that start with the exact same letters as user input will be output onto the table.
SOLVED- ANSWER BELOW
Your input in lowercase and it is stored in upper case
So change your query to convert the string into upper and then search
It is better to have upper in both sides of the where clause.
$query = "SELECT symSymbol, symName FROM symbols " .
"WHERE upper(symSymbol) LIKE '%".strtoupper($strSymbol)."%'";
What is this mess all about? Please see my comments in your code.
if(!$result)
{
print "Invalid Query Result<br />\n";
}
else
{
//============ This line is your main issue ============
$row = #$result->fetch_assoc(); //<-- pulling a row here advances the
//data set to row #2 (you never use the data from this row)
//======================================================
print "<table border='3' >\n";
print "<tr><th>Symbol</th>"
. "<th>Company Name</th>"
. "<th>Quotes Page</th" //<<--- unclosed </th>
. "<tr><th>History Page</th></tr>\n"; //<<--- misplaced <tr>
}//<<--- end if($result) block,
/*
anything below this is outside of the scope of the check for the result,
this will give you partial HTML and errors in the event of $result = false
*/
/*
because, you already advanced the dataset by one row, the loop starts on row 2
If you only had 1 row in your result set, then nothing is output from this block
While loops do not rewind, like a foreach ( besides I don't think you can rewind the DB result cursor )
*/
while($row = #$result->fetch_assoc())
{
extract($row); //<<--- avoid using this as it pollutes the scope, also where exactly are you using these variables it creates
print "<tr>";
print "<td>{$row["symSymbol"]}</td>";
print "<td align='right'>{$symName}</td>";
print "<td> Quotes Page</td>";
print "<td> History Page</td>";
print "</tr>\n";
}
print "</table>\n";
Lets start by cleaning that up
if(!$result){
print "Invalid Query Result<br />\n";
}else{
print "<table border='3' >\n";
/*
don't be afraid to indent or format things in a way that helps
keep track of the tags. Not like the "tab" police are going to
bust you for using all the tabs up.
*/
print "<tr>";
print "<th>Symbol</th>"
. "<th>Company Name</th>"
. "<th>Quotes Page</th>"
. "<th>History Page</th>\n";
print "</tr>\n";
while( $row = $result->fetch_assoc()){
/*
Try to use a consistent style for outputting, if possible.
*/
print "<tr>";
print "<td>{$row["symSymbol"]}</td>"
. "<td align='right'>{$symName}</td>"
. "<td> Quotes Page</td>"
. "<td> History Page</td>\n";
print "</tr>\n";
}
print "</table>\n";
}
You are basically throwing away the first row of your result set. When you call this ..}else{ $row = #$result->fetch_assoc(); .. you pull out the first row and move the internal pointer to row #2. Not only do you never use this data, but you overwrite $row with the value assigned in the while loop. Now while loops do not rewind back to the first result, so you pull row #2 and overwrite $row or you overwrite it with false. This is why when you have one match, you get none.
Some other thing to mention:
See how much clearer and concise my code is, well organized easy to read. Readability is the most important thing when coding ( IMO ).
Scope, keep the $result stuff inside the if block. If you don't do this then you're gonna have a bunch of errors, and invalid HTML.
Don't assign something if you are not gonna use it. While I understand, I was just "testing" that or "working" this out. That's all fine, but the first thing you should do when you have an issue, is go though your code, organize it and clean it up. Remove any "Fragments" from refactoring, and add comments to anything that is not clear just looking at the code it self.
Avoid using extract it pollutes your variable scope. That means you could overwite a variable without realizing it.
For example, say you have this code:
$name = 'John';
... bunch of other code ..
extract( $row );
... more code ...
echo $name; //outputs Tom
Now without being able to see the value of $row directly, you have no way to know that's what happened just by looking at the code. It's just a bad practice (IMO) to use it, because you don't want to use $row['name'].
Hope that helps.
I am updating all my code to Mysqli, before I did I had this code and it worked:
while($row = mysql_fetch_assoc($WildHorses)){
$InWild[] = $row['id'];
}
$RandomWild = array_rand($InWild);
$RandomHorse = $InWild[$RandomWild];
This is my SELECT statement:
$sql = "SELECT Horse.id, Horse.Name, Horse.Age, Horse.Image_name, Horse.Owner, Horse.Barn, Images.Image_path, Images.Image_name FROM Horse, Images WHERE Horse.Owner = '$colname_WildHorseList' AND Images.Image_name = Horse.Image_name";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " Name: " . $row["Name"]. " ImageName: " . $row["Image_name"]. "<br>";
}
} else {
echo "0 results";
}
The SELECT statement ends up echoing all of the correct information, but I want to make an array of only the Id's so that I can pick one at random each time a button is clicked.
I have tried multiple different copies and pastes of code to try and get what I want, but nothing seems to come out right.
Can someone point me in the right direction or explain what I'm doing wrong?
In your while loop you can simply do this :-
$i=0;
$animals=array();
$animals[$i]=$row["id"]; //puts id in array
And then you can create a random number by "rand()" between the length of 0-$i
and can get the job done.
JSFiddle here, with unfunctionaing PHP obviously, but on the local host it pulls through the information just fine.
I am trying to append data in a loop into a specific set of tags, inside a di of a certain class.
For example, for every row in the the table, add a div with the class "card" and append "Title" into a H2, "description" into a P tag etc.
Anyone know how I could go about doing this? I'm googling but finding it hard to phrase my question right.
Div "Card" markup:
<div class="card">
<h2>Health and Wellbeing</h2>
<p>Sometimes you just did too much sitting not enough jumping go go go.</p>
</div>
PHP pull:
$sql = "SELECT title, description, count FROM relevant_topics";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<b>Title: </b>" . $row["title"]. " - Description: " . $row["description"]. " " . $row["count"]. "<br>";
}
} else {
echo "0 results";
}
You can echo the div markup into the PHP code like this:
while($row = $result->fetch_assoc()) {
echo'<div class="card">
<h2>'.$row["title"].'</h2>
<p>'.$row["description"].'
</div>';
}
Not sure where you want the Row['count'] though.
Also you might wanna use PDO instead of mysql, Since mysql is outdated: How can I prevent SQL injection in PHP?
check this
if ($result->num_rows > 0) {
// output data of each row
while($row = $result-> mysql_fetch_array()) {//if not works change mysql_fetch_array() to fetch_assoc()
echo'<div class="card"><h2>';
echo '.$row["title"].';
echo '</h2><p>';
echo '.$row["description"].';
echo '</P></div>';
}
I'm trying to make a simple search engine using php & mysql . I know how get mysql result using php. Its Work.
ex : - Mysql database stored this (database table filed "meta")
I am having some difficulty with my PHP/MySQL search. It worked great
a year ago, but for some reason it has just stopped working. I have
tried searching and cannot figure it out. I have it echo my query but
it never adds in the WHERE clause. Any help is much appreciated. Form
Code: PHP Code:
Search word is searching
I Need to dispay search result like this
I have tried searching and cannot figure it out. I have it echo my
query but it never adds in the WHERE clause. Any help is much
appreciated. Form Code: PHP Code:
$query= mysql_query("SELECT meta FROM data WHERE LIKE '%searching%' ");
$count = mysqli_num_rows($query);
if($count >0){
while($row = mysqli_fetch_array($query)) {
echo "$row[id]'>$row[name]</option>";
$count =1;
}
else{
echo "<option value='' selected='selected'></option>";
}
mysqli_close($con);
From the code above here, there's a couple of issues that stand out:
The echo for the option doesn't have an open for , so it's not going to show.
When you're echoing information from the $row variable, you're referencing id and name, but the query is only outputting meta.
The query isn't searching on a field for the where clause, and is therefore failing
The code, from what I can see, should be changed to the following to work (assuming no other surrounding issues):
$query = mysql_query("SELECT meta, id, name FROM data WHERE meta LIKE '%searching%'");
$count = mysqli_num_rows($query);
if ($count > 0)
{
while ($row = $mysqli_fetch_array($query))
{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
$count = 1; // not sure why this needs to be here, but it's in your code so I'm keeping it there
}
}
else
{
echo "<option value='' selected='selected'></option>";
}
mysqli_close($con);
I have a small application which I have collecting user input and returning a set of results based on the input. The input is a postcode so for example, pl4 7by. Which has a space between it. This is the format of which the data is stored in. I wish to have applicable postcodes returned from the search even if a user inputs without the space between or multiple spaces.
This is currently what I have.
<?php
$input = $_GET["input"] . "%";
try{
$handler = new PDO();
}
catch (PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
$stmt = $handler -> prepare("
SELECT * FROM `LSOA_postcodes` WHERE postcode LIKE :input LIMIT 20
");
$stmt -> execute([
":input" => $input
]);
echo "<table>";
echo "<tr><th>Postcode</th><th>LSOA Code</th><th>LSOA Name</th></tr>";
while($row = $stmt -> fetchObject()){
echo "<tr>";
echo "<td>", $row -> postcode, "</td>";
echo "<td>", $row -> code, "</td>";
echo "<td>", $row -> name, "</td>";
echo "</tr>";
}
echo "</table>";
This is functional and returns the results regardless of case. I could store the data with no spaces, but I wish to have the correct format display to the user.
UPDATE
Just had a sudden thought and came up with this:
SELECT * FROM `LSOA_postcodes` WHERE REPLACE(postcode, ' ', '') LIKE REPLACE(:input,' ', '') LIMIT 20
This works as planned from first sight. Is there any problems that I cannot see with this?
Depending on the size of LSOA_postcodes, you may encounter performance problems using REPLACE as in the above 2 answers because it is unlikely to use index scans.
I would check the $input to see if it contains a space and add one if its length is > 3 - all in php then let the SQL do the search as in the original question.
You could trim the spaces on both sides of the = sign:
SELECT *
FROM `LSOA_postcodes`
WHERE REPLACE(postcode, ' ', '') LIKE REPLACE(:input, ' ', '')
LIMIT 20
Notes:
You'll use any benefit on an index on postcode, if you had one.
I stayed with the like operator like OP suggested, although since there are no wild cards here, a simple = should do the trick - Did not notice the use of % online 2, as per comments below.