Query PHP output suddenly only shows code, no values? - php

I recently had my eureka moment when I finished my first database connection. After closing my browser and reopening the html form, the output suddenly changed to code instead of the database values?
HTML form:
<form action="formulier3.php" method="post">
Hoogte: <input type="text" name="height"><br>
Breedte: <input type="text" name="width"><br>
<input type="submit">
</form>
PHP Page:
<?PHP
$user_name = "root";
$password = "root";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM price WHERE height = " . $_POST["height"] . " AND width = " . $_POST["width"] . "";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
print $db_field['ID'] . "<BR>";
print $db_field['value'] . "<BR>";
print $db_field['height'] . "<BR>";
print $db_field['width'] . "<BR>";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
This is my output:
"; print $db_field['value'] . "
"; print $db_field['height'] . "
"; print $db_field['width'] . "
"; } mysql_close($db_handle); } else { print "Database NOT Found "; mysql_close($db_handle); } ?>
Does anyone knows what's going on here?
Thank you in advance!

Somehow your server has stopped processing your php pages through the php processor (apache module or fastcgi or whatever).
What you see is the effect of presenting your php code as html. The fact that you don't see all your code but rather a small part of it, it is because the part from the first < (in <?php) until the first > (in print $db_field['ID'] . "<BR>"; is being parsed by the browser as an html tag and so it is not printed. If you look at the page source you'll see the full php code.
So there has been some server-side change that has produced that php files are directly server to the browser instead of parsed by the php engine.
One possible cause, is that you are developing in your local computer and when it worked you typed in your browser something like http://localhost/your_page.php but now you are opening the php file directly from the filesystem, so the browser shows something like file:///xampp/htdocs/your_page.php. You should always open your php pages through the web server (ie. using http://localhost/....) and never by double-clicking on the file in the file explorer.

Related

iTunes Search API: Update Notification

i'm using iTunes API Search and Advanced Custom Field WordPress plugin so the wp author can add a mac app id to a custom field and the implanted iTunes Search API above will add all the other information of app automatically in the wp post. and when app information updated my wp post will have the updated info like last verion number app size and ...
but the problem is my own wrote review and guide of any verion of any app inside my website and it need to be updated manually.
for example i have added a post for version 3.7.1 of "Things 3" mac app using method above to my WordPress and i have reviewed this version with my own description and hand-wrote in the post.
now i need to get notified when ever this app gets a new version or update so i can update my review and add some text for new version inside the post as well.
is there any way or method you guys can think of, so i can get notified when ever an app i have reviewed in my site gets an update ?
i really appreciate any way or taught !
Thanks.
There is no native API to do what you're asking.
However, with a little coding I believe you could use the RSS feed of the application to then create something to notify you on a change.
See Example for the App HomeScan
https://itunes.apple.com/lookup?id=1380025232
ID= YOURAPPID
I believe this should give you some general direction to do what you need.
This is a reply to our comment history in the other answer.
#erfanMHD, there are a number of ways to really do this. You don't have to do it in javascript. This isn't really something someone can give you an easy code snippet for since it requires a few additional things and is generally frowned upon in StackOverflow.
You'll need somewhere to store the localVersion of the application of the review you last wrote. In the example I wrote below I used a simple MySQL database to hold the local version. You'll also need to figure out how you want to display the data. I know you can add stuff to the wordpress dashboard but this isn't something we can show you how to do via StackOverflow.
However, below is a very simple (JUST FOR REFERENCE) purposes only on how one could achieve what you're trying to do. However this is just an example to guide you along the process.
For this demo, you'll need a MySQL database with a DBName of test and and a record created called application_version with 3 rows. ID, Name, Version.
<?php
$servername = "localhost"; // Your MySQL Server
$username = "root"; // Your MySQL Username
$password = "password"; // Your MySQL Password
$dbname = "test"; // The name of your MySQL database
$id = "904280696"; // The ID of the applicaiton you're wanting to check
function search($searchTerm){
// Construct our API / web services lookup URL.
$url = 'https://itunes.apple.com/lookup?id=' . urlencode($searchTerm);
// Use file_get_contents to get the contents of the URL.
$result = file_get_contents($url);
// If results are returned.
if($result !== false){
// Decode the JSON result into an associative array and return.
return json_decode($result, true);
}
// If we reach here, something went wrong.
return false;
}
function updateVersion($id, $name, $version) {
// Create MySQL connection
$conn = new mysqli($GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
// Check MySQL connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Save the Version information
$sql = "UPDATE application_version SET name='" . $name . "', version='" . $version . "' WHERE id='" . $id . "'";
echo $sql;
echo "<br>";
// Run the Insert into MySQL
if ($conn->query($sql) === TRUE) {
// Print On Success
echo "Record Updated Successfully";
echo "<br>";
} else {
// We dun goofed
echo "Error: " . $sql . "<br>" . $conn->error;
echo "<br>";
}
$conn->close();
}
function getLocalVersion($id) {
// Create MySQL connection
$conn = new mysqli($GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
// Check MySQL connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM application_version WHERE ID = " . $GLOBALS['id'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "Found Application ID Entry in database";
echo "<br>";
echo "<table><tr><th>ID</th><th>Name</th><th>Version</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["name"]."</td><td>".$row["version"]."</td></tr>";
$GLOBALS['storedVersion'] = $row["version"];
}
echo "</table>";
echo "<br>";
} else {
echo "No Application ID Entry found in database";
echo "<br>";
}
$conn->close();
}
// Search for your requested ID
$searchResults = search($GLOBALS['id']);
$currentVersion = '0.0.0';
$storedVersion = '0.0.0';
$appName = 'null';
// Loop through the results.
foreach($searchResults['results'] as $result){
// Pass the current version to variable
$currentVersion = $result['version'];
$appName = $result['trackName'];
// Get the current version or what ever else information you need
echo 'Current Version: ' . $currentVersion;
echo "<br>";
echo "<br>";
}
// Get Local Version from database
getLocalVersion($id);
if ($currentVersion > $storedVersion) {
echo "You have an old version friend";
echo "<br>";
// Write what you want it to do here
updateVersion($id, $appName, $currentVersion);
} else {
echo "You're all up to date";
echo "<br>";
// Write what you don't want it to do here
}
?>
Again, this is just quick and dirty. You'd want to do a lot of additional checks and balances. One I see right off the bat would be in the check for inserting.

Go to url based on mySQL query

Ok, so I'm making this website (kind of like bitly or goo.gl) where you enter a link and it shortens it, but with some extra goodies.
Right now I'm just hosting a local mysql server for testing, and the way it is setup, once a link is entered to shorten, a random 3 digit code is generated and put into the mysql table, along with its link.
When you enter the code on the site, it goes to the mysql table, finds the code, finds the corresponding link, and in theory is supposed to bring back that link, and then open it.
This is where the problem is. It simply does not work. I cannot figure out whether it is a problem with the html page, or with the scripting but I have no idea.
I'm not very experienced with PHP (language im using for query script) so I'm not sure how to go about troubleshooting.
I was hoping someone on here could offer some insight into why it may be not working.
All I know is when I click the "Go" button, it opens the php code rather than running it, and I'm not sure how to fix it.
Because of me not knowing exactly what the problem is, here is both the html and php code.
HTML:
(stripped down to just body for convenience. nothing interesting anywhere else)
<body>
<center><form action="sql_query.php" method="post">
<input class="enjoy-css" placeholder="" maxlength="3" name="var" type="text" />
<script type="text/javascript" script-name="josefin-sans" src="http://use.edgefonts.net/josefin-sans.js"></script>
<input type="submit" class="enjoy-css_1" value="Go" src="sql_query.php" />
<script type="text/javascript" script-name="josefin-sans" src="http://use.edgefonts.net/josefin-sans.js"></script>
</form></center>
PHP:
<?php
$servername = "localhost";
$username = "nimbleadmin";
$password = "admin";
$dbname = "nimble";
$var = $_POST['var'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysql_query("SELECT id, nimblecode, urlredirect, messageredirect FROM linker WHERE nimblecode = '" + $var + "'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo "id: " . $row["nimblecode"]. " //// URL: " . $row["urlredirect"]. " //// Message: " . $row["messageredirect"]. "<br>";
if ($row["messageredirect"]. == null) {
header('Location: ' . $row["urlredirect"]);
} else {
header('Location: http://nic.x10.mx/message?' . $row["nimblecode"]);
}
$conn->close();
?>
Any help is greatly appreciated! I know it's a bit of a interesting question, but I am still learning!
There is syntax error in your code, please use dot for concatentation in php and use mysqli object while querying instead of mysql.
$result = mysqli_query($conn, "SELECT id, nimblecode, urlredirect, messageredirect FROM linker WHERE nimblecode = '" . $var . "'");
Full Code changes: Store this file in the name as "tinyurl.php"
<?php
$servername = "localhost";
$username = "nimbleadmin";
$password = "admin";
$dbname = "nimble";
$var = $_GET['var'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query("SELECT id, nimblecode, urlredirect, messageredirect FROM linker WHERE nimblecode = '%s', $var);
if (!$result) {
echo 'Could not run query: ' . mysql_error(); exit;
}
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo "id: " . $row["nimblecode"]. "
//// URL: " . $row["urlredirect"]. "
//// Message: " . $row["messageredirect"]. "";
}
if ($row["messageredirect"] == "") {
header('Location: ' . $row["urlredirect"]);
} else if ($row["nimblecode"] != "") {
header('Location: http://nic.x10.mx/message?' . $row["nimblecode"]);
} else {
header('Location: http://nic.x10.mx/');
}
$conn->close();
?>
In .htaccess need to add this rule :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/?$ http://nic.x10.mx/tinyurl.php?var=$1 [QSA,NC,L]
Sample URL entry
http://nic.x10.mx/abc
Will redirect to the target URL present in DB.
If you can't run php code then check if apache's httpd.conf file has PHP MIME type uncommented, besides there are other things to consider. Check this Apache shows php code instead of executing

PHP Instant messenger

I am trying to make a messenger using PHP and SQL
This is my code
<form action="send_post.php" method="post">
<h3>Name:</h3>
<input type="text" name="name">
<h3>Message:</h3>
<input type="text" name="message">
<input type="submit">
</form>
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, message FROM chat";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
while(1){
ob_start();
echo "" . $row["name"]. " - " . $row["message"]. "<br>";
sleep(10);
echo "" . $row["name"]. " - " . $row["message"]. "<br>";
ob_end_clean();
}
}
}
$conn->close();
?>
However this does not work, is there any reason for this?
The problems started once I added the infinite while loop to refresh the messages.
PHP works serversided, which means that the client(guest) requests a page that the server then "compiles" to then send to the client as a clientsided language such as HTML. If the PHP code never reaches an end/stop the client browser is going to think the server stopped responding and give an error.
To achieve what you are trying to do you might want to look into something like JQuery AJAX which allows for the client to fetch data from the server seperatly from the main request. That way you can have one file showing only the messages and request that file on a timer, while having the form as usual page load. You can however also make the form dynamic using JQuery AJAX
UPDATE You can look at this blogpost to get an idea of what I'm talking about.

PHP block after html not executing

I have two blocks of code in the body section of an html ( .php) document. The code block before my heading executes, but the block after the heading does not. I've tried phpinfo(); in the first block and it runs fine. Try it in the second block and it doesn't. I have no idea why this could be. If anyone has suggestions I'm all ears.
I'm currently running xampp on a windows machine.
<body>
<?php
if (isset($_SESSION['ProfileID'])){
echo "<div style='text-align: right'>"
. "<a href='CZSN_Login.php'>Log "
. "Out</a></div>\n";
}
//here phpinfo() executes
?>
<h1>Chinese Zodiac Social Network</h1>
<?php
require_once("Includes/inc_ChineseZodiacDB.php");
//here phpinfo() will not execute
if (isset($_SESSION['ProfileID'])){
echo "<h2>Member Pages</h2>\n";
echo"<p>Below is a list of the members of the Chinese Zodiac Social"
. "Network. Click on a member's name to view that member's detailed information"
. "You may also choose to <a href='CZSN_MyProfile.php'>update your profile</a>.</p>\n";
$SQLQuery="select first_name, last_name, user_name "
. "from zodiac_profiles order by "
. "last_name, first name, user_name;";
$result=$DBConnect->query($SQLQuery);
if ($result===false){
echo $ErrorMsgs[];
}
else{
//This should never happen, but we can check anyway.
if ($result->num_rows==0){
echo "<p>There are no members to show.</p>\n";
}
Here is the code in my inc_ChineseZodiacDB.php file:
<?php
$ErrorMsgs = array();
$DBConnect = #new msqli("localhost", "root", "password", "chinese_zodiac");
if ($DBConnect->connect_error)
$ErrorMsgs[] = "The database server is not available."
. "Connect Error is "
. $mysqli->connect_errno
. " " . $mysqli->connect_error . ".";
?>
Try searching in require_once ("Includes / inc_ChineseZodiacDB.php"); there can be triggered die() or exit();
I guess you get "Error headers already sent", because of the title <h1>Chinese Zodiac Social Network</h1>. For phpinfo() to work there shouldn't be any output yet.
You are closing the php tag in the inc_ChineseZodiacDB file (i.e. you have ?> at the end of that file).
When your first file reads in the inc_ChineseZodiacDB file and sees the ?>, it interprets that as the end of your php section of code, and all the other code after require_once("Includes/inc_ChineseZodiacDB.php"); is ignored and read as regular html.
Remove that line, and your problem should be fixed:
<?php
$ErrorMsgs = array();
$DBConnect = #new msqli("localhost", "root", "password", "chinese_zodiac");
if ($DBConnect->connect_error)
$ErrorMsgs[] = "The database server is not available."
. "Connect Error is "
. $mysqli->connect_errno
. " " . $mysqli->connect_error . ".";
I figured out the ultimate problem. in the include file it reads:
<?php
$ErrorMsgs = array();
$DBConnect = #new msqli("localhost", "root", "password", "chinese_zodiac");
if ($DBConnect->connect_error)
$ErrorMsgs[] = "The database server is not available."
. "Connect Error is "
. $mysqli->connect_errno
. " " . $mysqli->connect_error . ".";
?>
where it should read:
<?php
$ErrorMsgs = array();
$DBConnect = #new mysqli("localhost", "root", "password", "chinese_zodiac");
if ($DBConnect->connect_error)
$ErrorMsgs[] = "The database server is not available."
. "Connect Error is "
. $mysqli->connect_errno
. " " . $mysqli->connect_error . ".";
?>
Note, I was calling msqli rather than mysqli. One simple typo...I'm still not understanding why the error messages were not being thrown for calling an undefined function. I added error_reporting(E_ALL); and ini_set('display_errors', 1); to the top of the file as well, and still no errors thrown. Either way, it works now. Thank you to everyone for the assistance.

Write PHP files through a PHP file from records in a mySQL database

The previous solutions working with MS Access did not pan out so I am trying this time with php.
I have this php file that opens a database, reads a list of records and creates an html file for each record, in their respective folder name (folder names also found in the record's fields)
The code seems to work but it doesn't go past the first record. I don't get any type of error message at all, so I am confused as to what the problem would be. I created the code out of many posts found here. The only thing I am wondering myself is whether the open and write functions (or whatever they are called) are in the correct sequence in the script. Perhaps the cause is something totally different.
Basically, what I am trying to do is for the script to create a "configuration" php file for each domain in its respective folder. The only difference between all the configuration files is the domainid field.
The table in the dbase is named domains. The fields are domainid which is an unique number; domain, which contains the domain name - e.g. domain.com - and it is used as the domain folder; and domaingroup, which is used as the "category" folder.
I changed all values for security purposes but the db connection works fine.
<?php
$db_name = "dbname";
$dbusername = "dbname";
$dbpassword = "password";
$server = "dbname.blahblahbla.hosted.com";
$connection = mysql_connect($server, $dbusername, $dbpassword) or die(mysql_error());
$db = mysql_select_db($db_name,$connection)or die(mysql_error());
$htmlquery = "select * from domains ORDER BY domain";
$htmlresult = mysql_query($htmlquery,$connection) or die(mysql_error());
$htmlinfo = mysql_fetch_array($htmlresult);
if ($htmlresult == 0) {
echo "<p>No Recourds Found</p>";
} else {
for ($i=0; $i <$htmlresult; $i++) {
$p = "<?php \n";
$p.= " //LS \n";
$p.= " define('Disable_Ads', 'No'); //Yes or No \n";
$p.= " define('Site_ID', ".$htmlinfo['domainid']."); \n";
$p.= " define('Short_Paragraph_Size',500);\n";
$p.= " define('Long_Paragraph_Size',1000);\n";
$p.= " ?> \n";
$htmlfolder = strtolower($htmlinfo['domaingroup']);
$htmldomain = strtolower($htmlinfo['domain']);
$a = fopen($htmlfolder."/".$htmldomain."/admin_config.php", 'w');
fwrite($a, $p);
echo $htmldomain." Completed <br />"; // TEMP - To try to see the looping of domain names
fclose($a);
}
}
?>
Thanks
Replace your for loop with a while loop
while($htmlinfo = mysql_fetch_assoc($htmlresult) {
$p = "<?php \n";
$p.= " //LS \n";
$p.= " define('Disable_Ads', 'No'); //Yes or No \n";
//.....
$htmlfolder = strtolower($htmlinfo['domaingroup']);
$htmldomain = strtolower($htmlinfo['domain']);
//...
}
Right now you are only fetching one row (you should also be calling mysql_fetch_assoc instead of mysql_fetch_array) so you are writing the same file x row times
Also please at very least upgrade to mysqli or preferably PDO as the mysql_* extension is deprecated
You need to iterate over all the rows.
After you query the database, you can do:
while($row = mysql_fetch_assoc($query)) {
$domain = $row['domain'];
$domaingroup = $row['domaingroup'];
// etc...
}
However, we don't recommend using mysql_* functions. Instead, use MySQLi at the very least, or PDO.
Based on the responses from both Kris and Rob, this is the corrected working code for those that may be seeking to do something similar (since I am not familiar with php nor mysql and this is just a temporary solution, others may look into what Kris and Rob suggested as far as "mysqli" and "PDO"). This for me worked perfectly. Thank you guys!
Kudos to #Kris since he replied with code example that was related to my post. He specifically used variables from my code, making it a lot easier to understand and troubleshoot; thus my point to his answer. ( I appreciate both of your input though)
<?php
$db_name = "dbname";
$dbusername = "dbname";
$dbpassword = "password";
$server = "dbname.blahblahbla.hosted.com";
$connection = mysql_connect($server, $dbusername, $dbpassword) or die(mysql_error());
$db = mysql_select_db($db_name,$connection)or die(mysql_error());
$htmlquery = "select * from domains ORDER BY domain";
$htmlresult = mysql_query($htmlquery,$connection) or die(mysql_error());
$htmlinfo = mysql_fetch_array($htmlresult);
if ($htmlresult == 0) {
echo "<p>No Recourds Found</p>";
} else {
while($htmlinfo = mysql_fetch_assoc($htmlresult) {
$p = "<?php \n";
$p.= " //LS \n";
$p.= " define('Disable_Ads', 'No'); //Yes or No \n";
$p.= " define('Site_ID', ".$htmlinfo['domainid']."); \n";
$p.= " define('Short_Paragraph_Size',500);\n";
$p.= " define('Long_Paragraph_Size',1000);\n";
$p.= " ?> \n";
$htmlfolder = strtolower($htmlinfo['domaingroup']);
$htmldomain = strtolower($htmlinfo['domain']);
$a = fopen($htmlfolder."/".$htmldomain."/admin_config.php", 'w');
fwrite($a, $p);
echo $htmldomain." Completed <br />"; // TEMP - To try to see the looping of domain names
fclose($a);
}
}
?>

Categories