PHP is preventing the rest of my page from loading properly - php

I am coding a book store for a school project. We started last semester with html. This semester we are converting it to php for dynamic reasons. I modularized the code the best I can, but when I put the functional section of php in, it prevents all the following html in the php code from displaying. As far as I can tell, I have done everything correctly and can not find the issue.
This is the php call in my index.php
<aside class="lSideMenu">
<table>
<tr><td><h3>Categories</h3></td></tr>
<?php
include_once 'getGenres.php';
popGenres();
?>
<tr><td>Humor</td></tr>
</table>
</aside>
I left the table row after the call for testing and does not show, but when I look at the debug window the table and aside close tags are there. there is other code after that that does not populate as well and my css breaks.
This is the php funtions of getGenres.php
<?php
/**
* Created by PhpStorm.
* User: PoeDawg
* Date: 4/5/2017
* Time: 2:51 PM
*/
function db_connect(){
$host = 'localhost';
$uname = 'root';
$pass = 'root';
$link = new mysqli($host, $uname, $pass);
if (!$link) {
die('Could not connect: ' . mysqli_error($link));
}
return $link;
}
function popGenres(){
$link = db_connect();
$dbname = 'volga_db';
$db_selected = mysqli_select_db($link, $dbname);
if (!$db_selected) {
die('Could not connect to database: ' . mysqli_error($link));
}
$query = 'SELECT * FROM tblgenres';
$result = mysqli_query($link, $query);
if ( $result ) {
while ( $row = $result->fetch_assoc() ) {
echo "<tr><td>" . $row['genreName'] . "</td></tr>";
}
$result->close();
}
mysqli_close()($link);
}
It does what it is supposed to in that it populates the list of genres, it just prevents the content below the function call from loading in the browser. If i take the php call section out, the page works as it should. Any help would be greatly appreciated.

Your last line of code should be like below,
mysqli_close($link);

Related

PHP and MySQL Nested database connection

This is a general example.
The application has 3 files.
conn.inc.php -- setting up the database connection
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "hmt";
$conn = new mysqli($db_host, $db_username, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
func.inc.php -- file including functions
<?php
function load_module($module_name){
$sqlCmd = "SELECT content FROM modules WHERE name='$module_name' LIMIT 1";
$result = $conn->query($sqlCmd);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$module_footer = $row["content"];
}
}else {
echo 'Error while loading module '.$module_name;
}
return $result;
$result->free_result();
}
?>
index.php -- the main page to display content
<?php
include 'conn.inc.php';
include 'func.inc.php';
if (!isset($_GET['page_name'])) { // if page_name is not set then reset it to the homepage
$page_name = 'module_footer';
}else{
$page_name = $_GET['module_footer'];
}
$module_content = load_module($page_name);
echo $module_content;
?>
Now my goal was to include functions inside the func.inc.php file and database into conn.inc.php, so as to keep separate and easier to read in the future.
My problem now is that the $conn variable declared in conn.inc.php cannot be used inside the function and it can't get my head around how to use it. I even tried using GLOBALS with no success.
The error for the files is this:
Notice: Undefined variable: conn in ./func.inc.php on line 4
Fatal error: Call to a member function query() on a non-object in ./func.inc.php on line 4
Which (I assume) is because the $conn variable is not in a global scope.
Now my question is. How can I keep the nested files but have the functions working? Is there a mistake in my approach or is it not possible to use a nested call to a mysql object?
Eventually you'll want to get into object-oriented coding but for now lets make what you have a little prettier.
When including files, you'll want to avoid things like global variables. They sound great, but end up being a pain when handling scope. So instead include a set of functions to call.
conn.inc.php
function getConnection(){
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "hmt";
$conn = new mysqli($db_host, $db_username, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
Then function.inc.php
<?php
function load_module($module_name){
$sqlCmd = "SELECT content FROM modules WHERE name='$module_name' LIMIT 1";
//Here is where we get our database connection.
$conn = getConnection();
$result = $conn->query($sqlCmd);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$module_footer = $row["content"];
}
}else {
echo 'Error while loading module '.$module_name;
}
return $result;
$result->free_result();
}
And finally finish up with your index page the way it is. So now, any page that wants a database connection will need to include the conn.inc.php and simply call getConnection() to get a mysqli connection object.
Think of your program as being a series of individual functions working together. And eventually you'll get to it being a series of objects working together. Nothing should be just floating off in global space. Try to encapsulate everything in some sort of function or object to be called over and over with consistent results.
You'd have to do something like this:
$conn = '';
function connect() {
global $conn;
... do db stuff
}
But this is usually bad practice. A more common method is to use a singleton object to "carry" your db handle, and you new that singleton everywhere you need to do DB operations.
function do_something() {
$conn = new DBSingleton();
... do db stuff
}

Using PHP to create dynamic forms with MySQL

I've searched the site and was unable to find an answer.
What I get in my script is an empty pulldown menu instead of the contents from the MySQL table. I'm developing/testing code in NetBeans 8.0.2 and running in Firefox 34.0.5. Here is my code (name of file is 'domains.php') and it is exactly as shown; I didn't leave anything out.
<body>
<form method="post" action="">
<select id="domain" name="domain">
<?php
// define connection variables
$DBServer = "localhost"; // server name or IP address
$DBUser = "xxxxxxxxx";
$DBPass = "xxxxxxxxx";
$DBName = "country";
$DBPort = "3306";
// create a connection to mysql
$conn = mysqli_connect ($DBServer, $DBUser, $DBPass, $DBName, $DBPort);
// check to see if a connection was made and, if yes, proceed
if (mysqli_connect_errno()) { // connection failed
echo "Database connection failed: " . mysqli_connect_error();
}
// the domain query to get all domain names
$domainQuery = "select domains from domains_subdomains_cop";
// run the query -- this works elsewhere to display the contents of a table
$resultD = mysqli_query($conn, $domainQuery) or die ("Query to get data from domain failed: "
. mysql_error());
// w/the exception of pulldown menu, the while loop works well to display records
// I've seen examples with MYSQLI_ASSOC and without it and I've tried both without success for
// pulldown menus. I use it because I haven't had any issues elsewhere in my program.
while ($row=mysql_fetch_array($resultD, MYSQLI_ASSOC)) {
$domainName=$row[DOMAINS]; // DOMAINS is the table attribute I'm trying to pull from
echo "<option>
$domainName // I accidentely put a ';' here once and that did show up in the pulldown
// menu.
</option>";
}
?>
</select>
</form>
</body>
Below is an object-oriented, mysqli prepared statements version
<form method="post" action="">
<select id="domain" name="domain">
<?php
$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName, $DBPort);
$stmt = $db->prepare("select `domains` from `domains_subdomains_cop`");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_object()){
echo "<option>".$row->domains."</option>";
}
?>
</select>
</form>

Connecting and inserting data into mysql table using php

I am a PHP newbie and have been trying for sometime now to connect to MySQL database using PHP so I can insert data into a table I have created but I am unable to do this.
I suspect the problem is coming from my PHP .ini file,but that's just me.
Would be grateful if anyone can help me configure my PHP .ini file so I can connect to MySQL and insert data into my table. Here is my PHP script in case you are wondering.
Any help will be gratefully appreciated.
<?php
$host ="localhost";
$username = "username";
$password = "password";
$database = "database1";
$table ="users";
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect:'.mysql_error());
}
mysql_select_db("database1",$con);
$mysql = "INSERT INTO $table(name,email,password)
VALUES('$_POST[name]','$_POST[email]','$_POST[password]";
if(mysql_query($mysql)) die(mysql_error());
echo"Data inserted";
mysql_close();
?>
I revised some of your code this should work. You had a bunch of little errors. I suggest you read a couple tutorials on just connecting and the syntax of php.
Here is some really basic examples of connecting to a database:
http://www.w3schools.com/php/php_mysql_connect.asp
Also once you get the hang of it here is a really good tutorial to teach you the OOP way of creating a class for a database:
http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/
As far as I see this is not an ini issue. I hope this helps.
<?php
//Set your variables
$host = "127.0.0.1";
$username = "username";
$password = "password";
$database = "database1";
$table = "users";
//Make your connection to database
$con = mysql_connect($host,$username,$password);
//Check your connection
if (!$con) {
die("Could not connect: " . mysql_error());
}
//Select your database
$db_selected = mysql_select_db($database, $con);
//Check to make sure the database is there
if (!$db_selected) {
die ('Can\'t use the db : ' . mysql_error());
}
//Run query
$result = mysql_query("INSERT INTO $table(name,email,password) VALUES('$_POST[name]','$_POST[email]','$_POST[password]'");
//Check Query
if (!$result) {
die("lid query: " . mysql_error());
}
echo "Data inserted";
mysql_close($con);
?>
First, why do you have <br/> in your PHP statements? Remove all those.
Also, you have to use PDO or mysqli_ instead of the mysql_ library, mysql_ is deprecated.

PHP database selection issue

I'm in a bit of a pickle with freshening up my PHP a bit, it's been about 3 years since I last coded in PHP. Any insights are welcomed! I'll give you as much information as I possibly can to resolve this error so here goes!
Files
config.php
database.php
news.php
BLnews.php
index.php
Includes
config.php -> news.php
database.php -> news.php
news.php -> BLnews.php
BLnews.php -> index.php
Now the problem with my current code is that the database connection is being made but my database refuses to be selected. The query I have should work but due to my database not getting selected it's kind of annoying to get any data exchange going!
config.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "test";
?>
database.php
<?php
class Database {
//-------------------------------------------
// Connects to the database
//-------------------------------------------
function connect() {
if (isset($dbhost) && isset($dbuser) && isset($dbpass) && isset($dbname)) {
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die("Could not connect: " . mysql_error());
$selected_db = mysql_select_db($dbname, $con) or die("Could not select test DB");
}
}// end function connect
} // end class Database
?>
News.php
<?php
// include the config file and database class
include 'config.php';
include 'database.php';
...
?>
BLnews.php
<?php
// include the news class
include 'news.php';
// create an instance of the Database class and call it $db
$db = new Database;
$db -> connect();
class BLnews {
function getNews() {
$sql = "SELECT * FROM news";
if (isset($sql)) {
$result = mysql_query($sql) or die("Could not execute query. Reason: " .mysql_error());
}
return $result;
}
?>
index.php
<?php
...
include 'includes/BLnews.php';
$blNews = new BLnews();
$news = $blNews->getNews();
?>
...
<?php
while($row = mysql_fetch_array($news))
{
echo '<div class="post">';
echo '<h2> ' . $row["title"] .'</h2>';
echo '<p class="post-info">Posted by | <span class="date"> Posted on ' . $row["date"] . '</span></p>';
echo $row["content"];
echo '</div>';
}
?>
Well this is pretty much everything that should get the information going however due to the mysql_error in $result = mysql_query($sql) or die("Could not execute query. Reason: " .mysql_error()); I can see the error and it says:
Could not execute query. Reason: No database selected
I honestly have no idea why it would not work and I've been fiddling with it for quite some time now. Help is most welcomed and I thank you in advance!
Greets
Lemon
The values you use in your functions aren't set with a value. You likely need to convert the variables used to $this->dbName etc or otherwise assign values to the variables used.
Edit for users comment about variables defined in config.php:
You really should attempt to get the data appropriate for each class inside that class. Ultimately your variables are available to your entire app, there's no telling at this point if the variable was changed by a file including config.php but before database.php is called.
I would use a debugging tool and verify the values of the variables or just var_dump() them before the call.
Your Database class methods connect and selectDb try to read from variables that are not set ($dbhost, $dbname, $con, etc). You probably want to pass those values to a constructor and set them as class properties. Better yet, look into PDO (or an ORM) and forget creating your own db class.

WebMatrix PHP mySQL

I am using WebMatrix Beta 3 which has support for php 5.2 and 5.3 I am able to run php pages but when I am trying to connect to mySql DB its not working.
Can anyone please suggest me the right way of doing it.
The connection code is written in a file called dbinfo.php which resides under config folder
<?php
$hostname = '127.0.0.1';
$username = 'root';
$password = 'password';
$database = 'test';
$link = mysql_connect($hostname, $username, $password)
or die("Could not connect : " . mysql_error());
mysql_select_db($database) or die("Could not select database");
//Below function added to allow customized unescaping.
function mysql_unescape($sRet_VAL=""){
$sRet_VAL = str_replace('\"','"',$sRet_VAL);
$sRet_VAL = str_replace("\'","'",$sRet_VAL);
return $sRet_VAL;
}
?>
and I am using this file as follows
<?php
require_once( $_SERVER['DOCUMENT_ROOT'] . '/config/dbinfo.php');
?>
<?php
$query = "SELECT * from temp";
$result = mysql_query($query)
or die("Error: " . mysql_error());
?>
it worked seems like webmatrix do not recognize I replaced it wilt <>php echo $varData ?> and it worked.

Categories