PHP script free of syntax errors won't fully parse [duplicate] - php

This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 4 years ago.
I have been struggling with this PHP script on my personal web server for quite some time. No matter what I do, or what input I give the HTML form (this PHP script is the action page for that form), I end up with a page that looks like this:
view larger version
Below is my code, which is supposed to get a list of ids of the recipes with a tag matching the user's query, then display a quick overview of the matching recipes to the user, in table format:
<html>
<body>
<title>Recipe Database</title>
<h1>recipe finder</h1>
</body>
</html>
<?
$servername = "localhost";
$username = "root";
$password = "xxxx";
$con = mysqli_connect($servername, $username, $password, "recipes");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$tag = $_POST["keyword"];
$query = mysqli_query($con, "SELECT id FROM recipes WHERE tag1 LIKE '$tag'");
$query2 = mysqli_query($con, "SELECT id FROM recipes WHERE tag2 LIKE
'$tag'");
$query3 = mysqli_query($con, "SELECT id FROM recipes WHERE tag3 LIKE'$tag'");
$result = mysqli_fetch_array($query);
$result2 = mysqli_fetch_array($query2);
$result3 = mysqli_fetch_array($query3);
$list = array_merge($result, $result2);
$list = array_merge($list, $result3);
if ($list[0] != ""){
echo "<table>";
for ($i = 0; $i < count($list); $i++) {
echo "<tr>";
$detailquery = mysqli_query($con, "SELECT * FROM recipes WHERE id LIKE
\"$list[$i]\"");
$details = mysqli_fetch_array($detailquery);
print "<h3>" . $details[1] . "</h3>";
print "<p>" . $details[2] . " minutes</p>";
print "<p>" . $details[3] . " servings</p>";
echo "</tr>";
}
echo "</table>";
} else {
echo "No recipe with that tag was found. Try a different tag.";
}
?>
I tested it on several different online syntax checkers and it came out clean. Yes, all other PHP scripts are running fine on my server. Yes, all the other PHP scripts are reading and writing to this database and others on my server without error. Yes, I did try wrapping body and html around the PHP script, it makes no difference. Yes, I have checked for unpaired quotation marks and apostrophes, there are none. Yes, I have tried storing the various queries in separate variables, that did not affect anything.
Any help would be appreciated, I am truly stuck on this one. Thank you!

Oops, it looks like I forgot to have the extended tag
<?php
instead of the short one without "php". My bad for being so oblivious.

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.

Output not displaying when attempting to connect to database

I recently set up a lamp server in an attempt to create a website. My code is as follows.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
<?php
$query = "SELECT * FROM nes";
$db = mysqli_connect('localhost','root','password','gameRankings');
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
while ($row < mysqli_fetch_array($result)) {
echo $row['ranking'] . ' ' . $row['name'] . ': ' . $row['review'] . ' ' . $row['releaseYear'] .'<br>';
}
mysqli_close($db);
?>
<h1>PHP connect to MySQL</h1>
</body>
</html>
The program runs fine and outputs the data I want when I run it using php index.php however when I go to load the site into a browser nothing displays except the heading. If I were to move my the $db connector line to the top of the code then not even the heading displays. There are no errors being thrown in the apache logs either. I have no idea what I'm doing wrong here!
Replace
$row = mysqli_fetch_array($result);
while ($row < mysqli_fetch_array($result)) {
With
while ($row = mysqli_fetch_array($result)) {
That will update $row each loop, with the value from database, and display the info you want.
Do these two steps and you will get your result .
Remove this statement :
$row = mysqli_fetch_array($result);
Re-write the while statement as :
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
//Your Code
}
If you still got no result , then check your database tables whether they have any records or not .
I wish I had a good answer as to what fixed this but I came in this morning to it functioning properly. I also made the other adjustments that were mentioned. This was my first post and I really appreciate the feedback everyone gave!

Use PHP to generate from an existing database for each row a new specific HTML that i already made

First I'm hitting on a wall here and I really could use your help. I coded the database so I have it all up and working plus all the data inside. I worked the HTML and the CSS media print query and I have it how I want it to look exactly. All I have to do now is:
for every row of the mysql select table I have to fill every specific input form
of the html page I made and print it
Can someone give me a hint of how I can do that?
Assuming you want to connect to your database and simply fetch the id you can do the following.
Ensure you change my_host, my_user, my-password, my_databse,my_tablewith your configuration settings. Then if you want to fetch anything else thanid` just change it to the column name you are looking for.
Be aware we are using PHP here.
// Open Connection
$con = #mysqli_connect('my_host', 'my_user', 'my-password', 'my_databse');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
// Some Query
$sql = 'SELECT * FROM my_table';
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query))
{
echo $row['id'];
}
// Close connection
mysqli_close ($con);
Check this link to get a in-depth explanation.
You can do this with two pages. One page gives you the overview and the other page gives you a print preview of your invoice.
The overview:
// DB select stuff here
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>\n";
echo " <td>".htmlspecialchars($row['what'])."</td>\n";
echo " <td>".htmlspecialchars($row['ever'])."</td>\n";
echo " <td>Detail</td>\n";
echo "</tr>\n";
}
The detail page:
$sql = 'SELECT your, columns FROM tab WHERE id = ?';
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
echo "There is no data for the given Id\n";
return;
}
echo "What: ".htmlspecialchars($row['what'])."<br />\n";
echo "Ever: ".htmlspecialchars($row['ever'])."<br />\n";

Creating a drop down list but the php won't work [duplicate]

This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 6 years ago.
So there's a lot of people helping to create a drop down list in html and populating it with their database. I'm trying to do this and I found some php code to do it but it just doesn't work. I understand php, sql and html but just not how they combine together. What seems to be the problem is that after the first echo, the rest of the code is just outputted as code to the page and it doesn't do anything. This is the code:
<html>
<body>
<?php
mysql_connect('localhost', 'root', 'password');
mysql_select_db('FoodMatching');
$sql = "SELECT IngID, IngName FROM Ingredient Characteristics";
$result = mysql_query($sql);
echo "<select name='Ingredient Name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['IngName'] ."'>" . $row['IngName'] ."</option>";
}
echo "</select>";
?>
</body>
</html>
And what I see on the webpage is:
"; while ($row = mysql_fetch_array($result)) { echo "
" . $row['IngName'] ."
"; } echo ""; ?>
There's no errors/warnings that pop up so I don't know what the problem is. Thank you if you can help :)
As mentioned you should look to use PDO's to talk to the DB.
If you get the list before the html is output then you can have much cleaner and easier to understand code
See if the below makes sense, you might need to make a few modifications as its untested.
There are some comments about your mySql, ensure that results are being returned when you run the query.
<?php
define( "DB_DSN", "mysql:host=localhost;dbname=foo");
define( "DB_USERNAME", "root");
define( "DB_PASSWORD", "password" );
// define the empty array to be filled from db
$aIngredeintCats = array();
// any other php tasks that dont needthe ingcats
// store sql
$sSQL = "SELECT IngID, IngName FROM IngredientCharacterisitics";
// create an instance of the connection
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// prepare
$st = $conn->prepare( $sSQL );
// if required securely bind any user input in the query
// $st->bindValue(":IngID", $sIngName, PDO::PARAM_STR);
// execute the connection
$st->execute();
/* this will show if a result has been returned from the db.
echo "<pre>";
var_dump($st->fetch());
echo "</pre>";
*/
// while myslq has rows loop over them and store
while($row = $st->fetch() ){
// use the IngID from db as the array key
// also strip any tags from the output. other sanatisation should be done
$aIngredeintCats[$row['IngID']] = strip_tags($row['IngName']);
}
// any other php tasks if they need the list of cats
?>
<html>
<body>
<form method='post' action='/'>
<?php
// if there are results stored create the select and loop over
if(!empty($aIngredeintCats)){
echo "<select name='IngredientName'>";
echo "<option value='' default>default</option>"
foreach ($aIngredeintCats as $iIngID => $sIngName) {
echo "<option value='".$sIngName."' >".$sIngName."</option>";
}
echo "</select>";
}else{
echo "<p>No results avaliable!</p>";
}
?>
</form>
</body>
</html>

Fetching rows in array using SELECT * FROM table WHERE IN

Hi I am trying to fetch data from a particular coloumn from all rows.
Eg Situation:
DB Data: id, fbid, name
$sql = 'SELECT id FROM table WHERE table.fbid IN (1234,5678,4321)';
$sql_run = mysql_query($sql);
$sql_fetch = mysql_fetch_assoc($sql_run);
print_r($sql_fetch);
This returns the data when I test it using Sequel PRO or PHPmyAdmin.
But when I print the array it only displays one value.
Can you help me with a solution or tell me where I'm going wrong?
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>
Before using a function, or - at least - when it does not what you expect - it's always a good idea to read the function description in the manual page.
PHP provides extremely easy access to its manual pages. All you need to type in the address bar is php.net/function name. It takes less time than typing whole question on Stack Overflow, yet you will get exactly the same answer. Think of efficiency.
You need to loop through each row
$sql_run = mysql_query($sql) or die(mysql_error());
while ($sql_fetch = mysql_fetch_assoc($sql_run)) {
print_r($sql_fetch);
}

Categories