Broken PHP web app (w/ Bluemix) - MySQLi stops script - php

I'm building a simple PHP webservice/webapp that when queried from an external application will return JSON formatted/encoded data from a MySQL database.
The PHP webapp and MySQL database are on Bluemix (and MUST to stay there).
Here is my current code for a typical PHP page:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Before Outside of php</p>
<?php
/*
* Following code will list all the customers
*/
echo "<p>Before Inside of php</p>";
$server = "Server";
$username = "username";
$password = "password";
$database = "database";
echo "<p>1 Inside of php</p>";
// Connecting to mysql database
$mysqli = new mysqli_connect($server, $username, $password, $database);
echo "<p>2 Inside of php</p>";
$response = array();
echo "<p>3 Inside of php</p>";
if ($result = $mysqli->query("SELECT firstName, lastName FROM customer")) {
while ($row = $result->fetch_array(MYSQL_ASSOC)) {
$response[] = $row;
}
echo json_encode($response);
}
echo "<p>4 Inside of php</p>";
$result->close();
$mysqli->close();
echo "<p>After Inside of php</p>";
?>
<p>Before Outside of php</p>
</body>
</html>
I have put in the <p>1 Inside of PHP<p> stuff in there so I could see where the script stopped and therefore figure out why.
The last thing that gets echo'd to the screen is <p>1 Inside of php</p> so therefore we can assume it's the MySQLi functions not working.
After some googling, I found that the main reason for this was that the MySQLi extension hasn't been included in the installation/build of the PHP webapp.
I am using this buildpack:
https://github.com/cloudfoundry/php-buildpack.git
which allows for use of a .bp-config/options.json file to include any extensions not included in the build pack.
As MySQLi is not included in the buildpack. My .bp-config/options.json file shows as follows:
{
"PHP_EXTENSIONS": ["mysqli"]
}
Now that MySQLi is included, I threw a phpinfo(); in my PHP before the MySQLi function, just to double check, and it displayed all the PHP information WITH a section titled: MySQLi.
Just to point out, the MySQLi section wasn't there before I wrote the .bp-config/options.json file.
However, the script STILL stops at the first MySQLi function and won't display anything after that. I'm stumped. Is it Bluemix's fault? Is it my PHP? Do I need to do something else before MySQLi is properly installed? I don't know, Help?

Your PHP is a little wrong on the line with mysqli_connect.
It should be $mysqli = mysqli_connect($server, $username, $password, $database);. Notice the reference to new is not used.
mysqli_connect is a function, not a class. What you want is either:
$mysqli = mysqli_connect(...);
or
$mysqli = new mysqli(...);
Both are equivalent.
Additionally the use of MYSQL_ASSOC should be MYSQLI_ASSOC.
Here is a full replacement of your code below.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Before Outside of php</p>
<?php
/*
* Following code will list all the customers
*/
echo "<p>Before Inside of php</p>";
$server = "Server";
$username = "username";
$password = "password";
$database = "database";
echo "<p>1 Inside of php</p>";
// Connecting to mysql database
$mysqli = mysqli_connect($server, $username, $password, $database);
echo "<p>2 Inside of php</p>";
$response = array();
echo "<p>3 Inside of php</p>";
if ($result = $mysqli->query("SELECT firstName, lastName FROM customer")) {
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$response[] = $row;
}
echo json_encode($response);
}
echo "<p>4 Inside of php</p>";
$result->close();
$mysqli->close();
echo "<p>After Inside of php</p>";
?>
<p>Before Outside of php</p>
</body>
</html>

Related

How to connect MySQL server without putting user/pass in the main page [duplicate]

This question already has answers here:
How to secure database passwords in PHP?
(17 answers)
Closed 2 years ago.
I have a main page on my site and I am trying to make a connection to the MySQL server and get some data from the database.
But the problem is that when I want to establish a connection I have to put the username and password in the page which doesn't seem wise to me.
I added a part of my code related to this problem.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";
$connection = new mysqli($host , $userName , $password , $dbName);
if ($connection->connect_error) {
die("Connection failed due to this error : " . $connection->connect_error . '<br>');
}
else{
echo "Connected successfully";
{
</body>
</html>
Put your connection code into another file, like connection.php and in every page you want to connect you should require_once "connection.php", also you could use variables from that file if you connect it, also instead of require_once you can use just require, but look at the internet differences between them
Normal practice is to put the mysql data in a separate php file. For example:
dbmain.php
<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";
$connection = new mysqli($host , $userName , $password , $dbName);
?>
then you can include this file in all php files which require db connection.
<?php include_once("dbmain.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
/// php commands, such as
//if ($result = $mysqli -> query("SELECT * FROM dbtable1")) {
// echo "Returned rows are: " . $result -> num_rows;
// Free result set
// $result -> free_result();
//}
//$mysqli -> close();
?>
</body>
</html>

How do i reorganize my php code to include separate db info file

Can any of you guys help me to reorganize this code? I'll try to explain the problem below.
I have a db_connection.php wich includes the following (just my db info and don't worry, i am just using it locally):
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=webappeind;charset=utf8','root','');
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
But the problem is i have the following file that also includes my db info, but i do not know how to reorganize my code to get it working with my separate php file.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webappeind";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM zoekopdrachten ORDER BY titel DESC LIMIT 3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output gegevens van elke rij
while($row = $result->fetch_assoc()) {
echo "<div class='recenttoegevoegd'>"."<a href='#'>".$row["titel"]."</a>"."</div>";
}
} else {
echo "0 resultaten";
}
?>
You can put the connection information in a separate file called, say, conn.php where you mention the code related to database opening, including credentials. Then, in the calling file, say putdata.php, you use the "require" or "require_once" command to include that conn.php. Let the conn.php file return a connection. Somewhat like this :
<?php
function GetMyConn() {
$server_name = "localhost";
$db_name = "db_name_goes_here";
$db_user = "user_name_goes_here";
$db_pass = "password_goes_here_muahhhaa";
$db_full_addr = "mysql:host=" . $server_name . ";" . "dbname=" . $db_name;
$MyConn = new PDO($db_full_addr, $db_user, $db_pass);
$MyConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $MyConn;
}
?>
In the calling file, you would say, something like :
require_once "GetConn.php";
$MyConnHere = GetMyConn();
$SqlHere = "Sql Statemetn goes here...."
$SqlHere2 = $MyConnHere->prepare($SqlHere);
$SqlHere2->execute();
Also, I suggest you can download the source code of some open source PHP application, such as mantissa, and see how they have organized their code files, folders and settings.

How do i connect to mysql server? and what do i use for the parameters?

Im trying to create a login for my website and i need to store emails, usernames, passwords, ect in a database i have created already using phpMyAdmin. I have gone through article after article and nothing seems to be working. i have my connect.php like this:
<?
$hostname = "localhost";
$username = "username";
$password = "password";
$databaseName = "_mySiteUserDataBase";
mysql_connect($hostname, $username, $password) or die("Cannot connect to server");
mysql_select_db($databaseName) or die("Cannot select database");
?>
And my main.php like this:
<?
include("connect.php");
$tableName = "myUsers";
$sql = "SELECT * FROM $tableName";
$result = mysql_query($sql);
?>
And i have created a simple form in my html like this:
<html>
<head></head>
<body>
<form>
<input type = "submit" action = "main.php" method = "post" value = "Login">
</form>
</body>
</html>
After submitting the form it says cannot connect to server. I am new to php and mysql and i dont understand what each parameter in the mysql_connect is, and i dont know what they do therefore im not sure what im supposed to enter in but everyone i keep reading about seems to be inputing random values? I could use a brief explanation on that, because i am stuck at connecting and cant even get past this point sadly enough. Also i have been reading that mysql_connect is deprecated and isnt valid anymore but i dont understand what im supposed to use as an alternative. I know its mysqli but thats it and im unclear of the syntax.
mysqli:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
echo "start<br/>";
try {
$mysqli= new mysqli('localhost', 'myusername', 'mypassword', 'dbname');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
echo "I am connected and feel happy.<br/>";
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
?>
If you need to know how to create users, what the heck the hostname is, how to grant access (often useful after the connect :>), just ask.
Try this code in 'connect.php'
<?php
error_reporting(0);
$con=mysql_connect('localhost','root','');// here 'root' is your username and "" is password
if(!$con)
{
echo 'not connect';die;
}
mysql_select_db('dbname',$con);// here 'dbname' is your database name
?>
And also try following code to include sql connection in your other php file(main.php)
<?php
include 'connect.php';
$sql = "SELECT * FROM myUsers";
$result=mysql_query($sql);
?>
Let me convert it to mysqli for you and maybe that will fix the problem. Also, make sure the username, password, and database name are correct.
Try this code. At very least, it will provide a better error message for debugging.
<?
$hostname = "localhost";
$username = "username";
$password = "password";
$databaseName = "_mySiteUserDataBase";
$con = mysqli_connect($hostname, $username, $password, $databaseName) or die(mysqli_error($con));
?>
Main.php
<?
include("connect.php");
$tableName = "myUsers";
$sql = "SELECT * FROM $tableName";
$result = mysqli_query($con,$sql);
?>

How to extract desired row from Mysql database using PHP script

I have created one HTML form which takes input from user ,Now I need to search user inputed name in Mysql database and print details related to that user inputed name which is stored in Mysql database.
Below script is creating HTML form to take user input, Saved as "ProcessTracking.html".
<form action="details.php" method="get"/>
<h3 align="center"><FONT color=#CCFF66>ENTER SO NUMBER</h3>
<p align="center">
<input type="text" id="SO_Number" name="SO_Number"/>
</p>
<div style="text-align:center">
<button type="submit" value="SEARCH">
<img alt="ok" src=
"http://www.blueprintcss.org/blueprint/plugins/buttons/icons/tick.png"/>
SEARCH
</button>
</form>
Below PHP script named as "details.php"
<?php
$userinput = $_GET['SO_Number'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ProcessTrackingSystem";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$result = mysqli_query($conn, "SELECT * FROM ProcessTrackingSystem.ProcessDetails WHERE SO_Number = '$userinput'") or die(mysqli_error($conn));
$row = mysqli_fetch_assoc($result);
#printf ("SO_Number: %s \n",$row["SO_Number"])
#print_r($row);
printf ("SO_Number:");
printf($row["SO_Number"]);
printf ('--||--');
printf ("Name:");
printf($row["Name"]);
printf ('--||--');
$conn->close();
?>
Firstlly you are not using the $_GET['SO_Number'] parameter in a WHERE of SQL statement. Secondlly you are using both mysql and mysqli which are totaly diffrent and don't work together. For usage see mysqli_fetch_row() and mysqli_query(). Also use print_r($row);.
Here is the corrected code:
<?php
$userinput = $_GET['SO_Number'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ProcessTrackingSystem";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$result = mysqli_query($conn, "SELECT * FROM ProcessTrackingSystem.ProcessDetails WHERE SO_Number = '$userinput'") or die(mysqli_error($conn));
$row = mysqli_fetch_row($result);
print_r($row);
$conn->close();
?>
EDIT: Added code example.
You have mixed mysql and mysqli api together. Try using either one.
Note: mysql api is deprectaed as of php 5.5.0
1st Error
As saty says it is because of the syntax error you have in this line
print_r"$row";
which should be as print_r($row)
2nd Error
You're mixing mysql & mysqli
I am not sure about the table that you have.
Recommendation :
I would recommend you to turn on the error_reporting if not those errors will be in your errors_log file
Also for debugging your sql, you can first construct your sql query, run in the phpmyadmin or related tools for your query, then fire the query and make this done.
Note :
If you are using these code in online then the error_log will be in the directory where you execute this page. (But it may change according to your hosting)
If you are running in local machine the error log may locate according to the server you use...
You can find by printing the php's configuration by phpinfo and find for
error_log
May this thing will fix your issue
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ProcessTrackingSystem";
$so = $_POST['SO_Number'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT * FROM ProcessDetails WHERE SO_Number=$so");
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
print_r($row[SO_Number]);
$conn->close();
?>

PHP Include another php that queries MySQL

In my site im trying to include on the top of each page a "banner" that is itself a separate php page that queries a MySQL database to return a number that displays.
When i goto the exact URL of the banner php url (www.sitename.com/banner.php) it works perfectly.
However, when i include the banner into another page include'banner.php' it returns the following error: Database access error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
I have 2 ways i need to include this, my main site pages are all php. My forum is phpbb and the file i need to include is HTML so i used (Note, i did ../ back out to the banners root, its not a matter of my file not being found.
Im assuming that when including the scope is different. How would i correctly accomplish this include?
Banner.php
<?php
require("../mysql.inc.php");
check_get($tp, "tp");
$tp = intval($tp);
$link = sql_connect();
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
if (!$result) {
echo "Database error.<br>\n";
exit;
}
list($total) = mysql_fetch_row($result);
mysql_free_result($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="menu_css.css" media="screen"/>
</head>
<body>
<div class="menucenter">
<div class="Online"> <? echo"$total" ?> Online</div>
</body>
</html>
mysql.inc.php
<?php
$SQLhost = "****.db.****.hostedresource.com";
$SQLport = "3306";
$SQLuser = "****";
$SQLpass = "****";
$SQLdb = "****";
function sql_connect()
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
if ($SQLport != "")
$link = #mysql_connect("$SQLhost:$SQLport","$SQLuser","$SQLpass");
else
$link = #mysql_connect("$SQLhost","$SQLuser","$SQLpass");
if (!$link) {
echo "Database access error ".mysql_errno().": ".mysql_error()."\n";
die();
}
$result = mysql_select_db("$SQLdb");
if (!$result) {
echo "Error ".mysql_errno($link)." selecting database '$SQLdb': ".mysql_error($link)."\n";
die();
}
return $link;
}
function sql_query($link, $query)
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
$result = mysql_query("$query", $link);
if (!$result) {
echo "Error ".mysql_errno($link).": ".mysql_error($link)."\n";
die();
}
return $result;
}
function check_get(&$store, $val)
{
$magic = get_magic_quotes_gpc();
if (isset($_POST["$val"])) {
if ($magic)
$store = stripslashes($_POST["$val"]);
else
$store = $_POST["$val"];
}
else if (isset($_GET["$val"])) {
if ($magic)
$store = stripslashes($_GET["$val"]);
else
$store = $_GET["$val"];
}
}
?>
#Craig, there is a possibility that the include file contains other includes which are not getting the right path. Can you paste some codes of the include file for us to validate the error ?
EDIT:
You have a missing quote at the end of the query.
$result = sql_query($link, "SELECT COUNT(*) FROM online_count);
It should be
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
EDIT:
You have a problem with the quotes. See you check_get function. $val is a variable and you dont need quotes around it. Check the below code.
if (isset($_POST[$val])) {
if ($magic)
$store = stripslashes($_POST[$val]);
else
$store = $_POST[$val];
}
else if (isset($_GET[$val])) {
if ($magic)
$store = stripslashes($_GET[$val]);
else
$store = $_GET[$val];
}
EDIT:
Also remove the quotes from $query:
$result = mysql_query($query, $link);
First things first:
Remove the # from your mysql statements and see if you are getting any other errors related to variables or so. You should not suppress errors while debugging.
Try printing the host, port, user and password variables inside the sql_connect() function and see if you are getting the correct values in your function.
If you have access to your server, check if /var/lib/mysql/mysql.sock exists, and has sufficient permissions.
srwxrwxrwx 1 mysql mysql 0 Sep 21 05:50 /var/lib/mysql/mysql.sock
If all is well till this point, you might want to troubleshoot your MySQL service further. A restart would help flush the connections, if that is the issue. Check a similar thread in SO too.

Categories