PHP MySQLi query function parsed incorrectly - php

I'm trying to fetch data from my MySQL database and display it on a simple webpage.
However when i add the PHP code to the .html file it almost looks like the code isn't parsed as PHP.
The code below connects to the db (which works), I enter a query and then fetch the results.
However given the output it almost looks like the -> in $conn->query($query) is enterpreted as ?>
The page resulting from the code below shows these three lines of text:
query($query)) {while ($row = $result->fetch_assoc()) {echo '
'.$row['Title'].'
';>$result->free();}else"fail";}?>
Which is in accordance to the format i want, but obviously not what intended.
However i get the same resulting page from this code when i remove everything from the second line till $conn->.
Which gives me the impression that the code followed by $conn-> isn't read as PHP code at all.
I think it's also important to note that i don't have this problem in a different part of my page, i.e. creating a database connection works fine and code followed by the query is parsed as i would expect.
Is my assumption correct and how can i counter this? Or have a missed something obvious causing this error?
<div class="col-sm-8 blog-main">
<?php
$servername = "localhost";
$username = "root";
$password = "marvin";
$dbname = "blogpostdb";
$conn = new mysqli($servername, $username, $password, $dbname);
$query = "SELECT * FROM posts";
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
echo '<div class="blog-post">
<h2 class="blog-post-title">'. $row['Title'] .'</h2></div>';
}
$result->free();
}
else{
echo "fail";
}
?>
</div><!-- /.blog-main -->

You need to change the extension from .html to .php.
Files with the .html extension won't parse PHP, unless the webserver is configured to do so.

Related

How to create a simple dropdown list with php linking to mysql database

Hi there Im very new to PHP and Im having issues trying to make drop-down list with php connecting to my mysql db. I am able to connect to the database no problem as no error message is showing up when I load up the php document online.
However from my research I just cant seem to find what Im looking for. I have made a table in mysql with the necessary ids and values. Below is my code within select tags if even thats a good way to do it? if anyone can help much appreciated.
<select>
<?php
$db = mysqli_connect ("host", "username", "password");
if (!$db)
{
echo "Sorry! Can't connect to database";
exit();
}
//table name on mysql db = users3
?>
</select>
It looks like you're trying to run PHP inside of an HTML select tag. PHP runs server side (in the background).
You'll need to create your dropdown menu using Javascript and HTML, then have have your javascript code call your PHP via AJAX. There are a number of ways doing this, but the basic idea is to have an event bound to each item in your dropdown list. When you click one of your list items, your javascript uses AJAX to call your PHP which queries the database.
That's a pretty high level description of it but hopefully it gives you a sense of where you need to go from here.
Regards,
--Drew
Your code is obviously missing any SQL select query.
The following code was adapted from W3Schools, I suggest you have a read over some examples using mysqli here Mysql select query example
Included is a select list that is also courtesy of W3Schools, HTML form elements
I implore you to read some examples at W3Schools.
HTML
<select name="items"><?php echo getSelectItems(); ?></select>
PHP
<?php
function getSelectItems() {
$servername = "host";
$username = "username";
$password = "password";
$dbname = "itemDB";
$output = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT itemName FROM items";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$output .= '<option value="' . $i . '">' . $row["itemName"] . '</option>';
$i++;
}
}
$conn->close();
return $output;
}

JSON_ENCODE encoding contents of included php file

Having a weird issue with JSON_ENCODE. I am using php to retrieve data from a database and JSON to pass it to Javascript. It was working perfectly until I included another php file that I intend to use to do some processing on the data before it is returned. After including the file JSON started encoding both the data returned and the contents of the file that I included.
php code:
<?php
include("GeoLocation.php");//STATEMENT CAUSING JSON TO ACT WEIRDLY
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "go_with_your_mood";
//$lat=(isset($_GET['lat']))?$_GET['lat']:'';
//$long=(isset($_GET['long']))?$_GET['long']:'';
//$geo = new GeoLocation();
$mysqli = new mysqli('127.0.0.1', $dbuser, $dbpass, $dbname);
//Select Database
//mysql_select_db($dbname) or die(mysql_error());
//build query
$query = "SELECT * FROM service where service_type = 'security' limit 5";
//Execute query
$qry_result = $mysqli->query($query);
//initial array to encapsulate each individual row
$jsonArray = array();
// Insert a new array for each row returned
while($row = $qry_result->fetch_assoc()){
$rowArray = array($row["id"],$row["name"],$row["address"],$row["suburb"],$row["postcode"],$row["phone"],$row["latitude"],$row["longitude"],$row["description"],$row["service_type"]);
array_push($jsonArray, $rowArray);
}
echo json_encode($jsonArray);
?>
data that is returned from this file:
Data that should be returned:
336,TERANG PUBLIC HOSPITAL,13 AUSTIN AVENUE,TERANG,3264,,-38.23939895629883000000,142.90240478515625000000,,medical,
337,ALFRED PUBLIC HOSPITAL,55 COMMERCIAL ROAD,MELBOURNE,3004,,-37.84560012817383000000,144.98210144042970000000,,medical,
338,CAULFIELD PUBLIC HOSPITAL,260 KOOYONG ROAD,CAULFIELD,3162,,-37.88240051269531000000,145.01669311523438000000,,medical,339,NORTHERN PUBLIC HOSPITAL,185 COOPER STREET,EPPING,3076,,-37.65259933471680000000,145.01510620117188000000,,medical,340,MAFFRA PUBLIC HOSPITAL,42-48 KENT STREET,MAFFRA,3860,,-37.96120071411133000000,146.98339843750000000000,,medical
Does anyone know why JSON is returning the contents of the included file as well as my data?
Seems like short tags <? are disabled. And looks like your geolocation.php file starts with <? instead of <?php
Either edit your geolocation.php file and replace <? with <?php in the start.
Or include it like following
include( 'GeoLocation.php' );
Meaning include it by putting space before and after or copy paste the include code at it is written above. Hopefully one of these solutions work.
Alternatively, if you can then enable short tags.

PHP MySQLi to HTML combobox

I'm trying to pass data from a MySQL database to a HTML combobox and i'm using php to do that
<form method="POST">
<select class="js_inline_input">
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "js_milhoes";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
echo "<option> Connected successfully </option>";
}
$sql = "SELECT * FROM js_country";
$result = $conn->query($sql);
while($row=mysqli_fetch_assoc($result)){
//My Personal echo
echo "<option value='".$row['countryCode']."'>".$row['countryName']."</option>";
//Echo i saw on this site
echo "<option value='{$row->countryCode}'>{$row->countryName}</option>";
}
$conn->close();
?>
</select>
</form>
It should list all the countries in the combobox but what displays is:
- From first echo: ".$row['countryName']."
- From second echo: {$row->countryCode}
I already check the connection, and before i add a if that says that the query is not empty
The reason why your second <option> isn't showing is because you are using a "fetch object" syntax $row->column.
http://php.net/manual/en/mysqli-result.fetch-object.php
You need to use one or the other; not both.
Either you use
while($row=mysqli_fetch_assoc($result)){
echo "<option value='".$row['countryCode']."'>".$row['countryName']."</option>";
}
or (and escaping with double-quotes):
while($row=mysqli_fetch_object($result)){
echo "<option value=\"{$row->countryCode}\">{$row->countryCode}</option>";
}
You also need to note that column names are case-sensitive when iterating over those like that.
Meaning that, countryCode and countrycode are two different animals here, as is countryName and countryname; should it be the case.
Check for errors on your query.
Footnotes:
You state: "but what displays is: - From first echo: ".$row['countryName']." - From second echo: {$row->countryCode}"
I don't understand what you mean by that. I've tested your code and it works fine (besides the "fetch object" syntax issue). If what you mean by that is you are seeing "code" rather than being parsed, then you are either not using a webserver, or that you are accessing it as file:///file.php rather than http://localhost/file.php or as .html should this be the case as the file extension is unknown.
That is my conclusion for this question.
Ok, this was a stupid problem, when i changed from wamp 2.5 to wamp 3 i forget to delete the wwamp paste and i had 2, so i has using the wrong fill and because that one wasn't in a server with apache the browser comments the php

php if statement always returns false

I know this is a really basic question but I am completely at my wits end. I have been working on this for two days. The if statement always returns false. I have tried === and == and copy to an $array and process outside the fetch $result loop. I have compared to a direct "name". I have outputed the ascii value of each letter of the returned string and compared that way to make sure I wasn't putting a space or something in somewhere. I've tried mysql and mysqli ways. I've tried OO style and Procedural style but here's the rub, This code was copy and pasted from my own site where it's working just fine in three other programs in my site.
<?php
SESSION_START();
if(!isset($_SESSION["uname"])){
require ('redirect.html');
die();
}// session is set close
$uname = $_SESSION["uname"];
$user_name = "xxxxxx";
$password = "xxxxxxx";
$database = "usersdata";
$server = "xxxxxxxxxx.ipagemysql.com";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM messages";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
//echo out values for visual comparison
echo $db_field['recipient']." ".$uname." ";
if($db_field['recipient'] === $uname){echo " match ";} else {echo " no match ";}
}// while loop db_field close
}// if db_found loop close
mysql_close($db_handle);
?>
As I stated this code works just fine in three other programs running on this very site. All I did was copy paste and change the db and fields. I even tried retyping it all from scratch just to make sure. Help me I'm melting....
Why would you return all the messages and then compare with every single message if the name matches. You can simply add a where clause to your query
SELECT * FROM messages WHERE recipient='uname value here'
Then you can check for the number of rows returned. If 0 rows are returned, there was no match.

wrong '.$row["column_name_here"].' encoding

I'm a bit newbi in PHP. I implemented http://www.sanwebe.com/2013/03/loading-more-results-from-database solution in my new website: http://do2go.pl/do2go-nowa/
its working well - except encoding. My DB and all things are in UTF8. When fetch taking data from DB UTF8 seems not working.
Heres configuration and fetch code:
Config:
<?php
$db_username = 'kamio2_do2gonowa';
$db_password = 'JeremiasZ1!';
$db_name = 'kamio2_do2gonowa';
$db_host = 'localhost';
$item_per_page = 2;
mysqli_query ("SET NAMES 'utf8'"); mysqli_set_charset('utf8');
$connecDB = mysqli_connect($db_host, $db_username, $db_password,$db_name) or die('could not connect to database');
?>
And fetch:
<?php
include("config.inc.php"); //include config file
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
header('Content-Type: text/html; charset=UTF-8');
//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
header('HTTP/1.1 500 Invalid page number!');
exit();
}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($connecDB, "SELECT id,introtext FROM w7wst_content ORDER BY id DESC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo '<li id="item_'.$row["id"].'"><span class="page_message">'.$row["introtext"].'</span></li>';
}
echo '</ul>';
?>
I added mysql_query ("SET NAMES 'utf8'"); mysql_set_charset('utf8'); but this does nothing. Still getting � symbols and ? instead of " All next 3 was changed directly in DB tables for html symbols which isn't a solution.
Any help appreciated! :)
(To close the question, since this was the solution to the OP's problem)
Add $connecDB->set_charset("utf8"); just before $results = mysqli_query($connecDB...
You are using mysql and mysqli in one script. Only use mysqli as mysql has been deprecated. That said try this:
mysqli_character_set_name($connectDB);
mysqli_set_char_set($connectDB, 'UTF8');
Set these after your connection script.
Did you check if they are properly stored in the table? Try typing this in your database(not in PHP):
SELECT * FROM w7wst_content;
and see if it's displaying properly. Alternatively you can check table contents with some tool like phpmyadmin. If it's not you have to set collation to something like utf8_general_ci.
EDIT: Also, how about setting the charset AFTER connecting to the database, hm? :)

Categories