PHP block after html not executing - php

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.

Related

What I'm doing wrong? "cronjob"

I have MySQL database, it contain a table with a column called "downloads"
I want to update this column to 0 every 24h, but it seems my code doesn't work!
I have folder on the server named cron.
Inside it there is two files, one to connect to the database, and the other contain the php code to reset the column downloads to 0
This is my connection code:
<?php
$link = mysqli_connect("localhost", "test", "root", "test1");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;
?>
And my php code that I want to use it in cronjob is this one:
<?php
require_once('/home/cron/connect.php'); // connect to db
$mysqli = ("update users set downloads = 0");
$mysqli->close();
?>
I fired the file directly from the browser but it doesn't reset the column downloads to zero! what I'm doing wrong?
Note: of course there is .htaccess file to protect direct access to the connection file
EDIT: There is no error at connection if I run the code of connection, but the second code from cronjob doesn't work!
You do not need $mysqli->close(); at all. Your connection object is called $link. The second line should be:
$link->query("update users set downloads = 0");
You should probably also check if it executed properly and if not do something about it.
Your full code in second file could look like this (assuming the connection is successful):
<?php
require_once('/home/cron/connect.php'); // connect to db
if( $link->query("update users set downloads = 0") ){
// succesful
} else {
// fail
}

PHP cannot connect to mysql after moving DB & website to the same machine

I updated my server & moved both server itself & website on the same machine.
After doing that, my website won't connect to DB anymore.
I'm using Ubuntu 16.04 on aws
I'll include connection script, because a friend said my code might be too old for php 7. Other then that I'm looking for any suggestions which might result in fixing my problem.
include "../config.php";
$link = #mysql_connect($db_host, $db_user, $db_pass);
if (!$link)
{
$error = "Cannot access MYSQL, please contact admin!<br />";
$error .= mysql_errno() . ": " . mysql_error();
die($error);
}
$db = #mysql_select_db($db_name);
if (!$db)
{
$error = "Failed to select database.<br />";
$error .= mysql_errno() . ": " . mysql_error();
die($error);
}
$lang = #mysql_query("SET NAMES utf8");
# is an error control operator. It means to php "if this call fails, let's log nothing and let's continue the trip"
So remove those # symbols before your mysql calls then see your logs.
Anyway those mysql calls won't be accepted by php7.
You have now to use PDO or MySQLi
http://php.net/manual/en/function.mysql-connect.php

Connection to database shows blank page

I have a file login.php to try to connect to my database.
I put the file login.ph inside the server folder and started the server.
Then i call the file in the browser and it shows a blank page. It does not respond even if i change the values of the database to an incorrect value.
I don't know if the error is inside the code or if it is another problem.
Thanks.
login.php:
<?php
$username = $_GET['fname'];
$password = $_GET['fpass'];
$con=mysqli_connect("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qz = "SELECT contact_id FROM contacts" ;
$qz = str_replace("\'","",$qz);
$result = mysqli_query($con,$qz);
while($row = mysqli_fetch_array($result))
{
echo $row['contact_id'];
}
mysqli_close($con);
?>
You must check $con variable that you have set with the result of the connection:
if (!$con) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
Do you have web server (say apache) installed and running on your server? You have to. Then put your file on the web server folder (say /var/www/html) and test in the browser.

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

Mysql create database failed (kind of)

CREATE DATABASE 'some database name' ;
Works as expecting using mysql's client.
The same query (different database name) from php/mysqli - fails kind of.
It writes to the INFORMATION_SCHEMA.SCHEMATA
But fails to write to the mysql.db table?
This is actually an issue of a larger problem.
What is going on. Why does my mysqli fail?
code:
$mysqli = new mysqli("p:127.0.0.1", "root", "showtech123", "mysql");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if(!$mysqli->query( "CREATE DATABASE $database_name;"))
{echo "DATABASE encountered error:" . $mysqli->error . "<br /";}
Errors:
db_name: terarydatabase3333, un:teraryuser5999
Warning: mysqli::query(): MySQL server has gone away in /www/admin.showtechllc.com/public_html/adddb.php on line 21
Warning: mysqli::query(): Error reading result set's header in /www/admin.showtechllc.com/public_html/adddb.php on line 21
USER encountered error:MySQL server has gone away
the fourth parameter in the constructor is the database you want to use.
you're actually trying to create a new database inside an existing one.
try this :
$mysqli = new mysqli("p:127.0.0.1", "root", "showtech123");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}else{
echo "connected";
}
if(!$mysqli->query( "CREATE DATABASE $database_name;")){
echo "DATABASE encountered error:" . $mysqli->error . "<br /";
}else{
echo $database_name . "created";
}

Categories