PHP MySQL function dies - php

Ive written my function just to check if the database connection is working.
And it seems like he cant connect to my database, thats no problem, but he dies at the point where i run the function.
function testconnection() {
global $dbhost, $dbuser, $dbpassword, $dbname;
error_reporting(E_ERROR);
$conn = mysql_connect($dbhost, $dbuser, $dbpassword);
$dbconn = mysql_select_db($dbname);
if ( !$conn ) {
return "connfailed";
}
if ( !$dbcon ) {
return "dbconnfailed";
}
}
It stops any further building of the website.
All variables are defined. This function is just used to display an error message if it returns "dbconnfailed".
but even with echo testconnection(); it displays nothing.
can be seen here
but I host this at a big company and on localhost via xampp
it isnt working on one.com but it is working on xampp

You did not add your connection to $dbconn
$dbconn = mysql_select_db($dbname,$dbconn);
Pls Don't use the deprecated and insecure mysql_*-functions. They have been deprecated since PHP 5.5 (in 2013) and were completely removed in PHP 7. Use MySQLi or PDO instead

If you are using mysqli: Try this one..
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM usertable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();

use mysqli library
function testconnection() {
global $dbhost, $dbuser, $dbpassword, $dbname;
error_reporting(E_ERROR);
$conn = mysqli_connect($dbhost, $dbuser, $dbpassword);
/* check connection */
if (mysqli_connect_errno()) {
return "connfailed " . mysqli_connect_error();
}
$dbconn = mysql_select_db($dbname);
if(!$dbcon) {
return "dbconnfailed " . mysqli_error($dbconn);
}
}

Related

How to connect html to Azure database?

I'm trying to connect my Azure Sql storeage and html to show everything i have. but i'm having some trouble. i researched w3school and other resources but i still don't know what is wrong?
so i use Notepad++ and save it as html and use php to establish the connection
here is the code in my notepad+++ so far:
<?php
$servername = "servername*****.mysql.database.azure.com";
$username = "loginfor****n#mysql***";
$password = "*****";
$db = "db";
// Create connection
$conn = new mysqli($servername, $username, $password. $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
and this is what i got
connect_error) { die("Connection failed: " . $conn->connect_error);
i have no idea where did i went wrong. please help me if you can, thanks
I'm not 100% sure as I'm not a PHP dev, but Microsoft have the following on their Azure documentation (here):
<?php
$serverName = "your_server.database.windows.net"; // update me
$connectionOptions = array(
"Database" => "your_database", // update me
"Uid" => "your_username", // update me
"PWD" => "your_password" // update me
);
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
$tsql= "SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName
FROM [SalesLT].[ProductCategory] pc
JOIN [SalesLT].[Product] p
ON pc.productcategoryid = p.productcategoryid";
$getResults= sqlsrv_query($conn, $tsql);
echo ("Reading data from table" . PHP_EOL);
if ($getResults == FALSE)
echo (sqlsrv_errors());
while ($row = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC)) {
echo ($row['CategoryName'] . " " . $row['ProductName'] . PHP_EOL);
}
sqlsrv_free_stmt($getResults);
?>
My guess is that your PHP is malformed and you're getting a render of the code rather than it actually properly executing - be sure to read the documentation.
i've also tried this code too
<?php
$host = '****.mysql.database.azure.com';
$username = '****#mysql****';
$password = '****';
$db_name = '*****';
//Establishes the connection
$conn = mysqli_init();
printf("hello")
mysqli_real_connect($conn, $host, $username, $password, $db_name, 3306);
if (mysqli_connect_errno($conn)) {
printf("sory");
die('Failed to connect to MySQL: '.mysqli_connect_error());
}
// Run the create table query
if (mysqli_query($conn, '
select * from table1;
')) {
printf("Table created\n");
}
//Close the connection
mysqli_close($conn);
?>
it returns a blank page, i feel that some how it just skip all of my php code

Cannot execute database statement from another php file using include

What I'm doing wrong after adding class define to StoreUser.php file and calling it from store.php file because it doesn't work any moore? It worked fine inside file StoreUser.php without class define and function see below.
$dbhost = "localhost";
$dbname = "riskinarviointilomake";
$dbuser = "root";
$dbpass = "";
//private $email;
if(isset($_GET["email"])){
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (!( $stmt = $conn->prepare("INSERT INTO users(unique_id,email,
encrypted_password) VALUES(?,?,?)"))){
echo "Table creation failed: (" . $conn->errno . ") " . $conn->error;
}
$stmt->bind_param('sss', $unique_id,$email,$password);
$unique_id=123457764;
$password="df12467hh";
$result = $stmt->execute();
$stmt->close();
$conn->close();
}
?>
This doesn't work
class StoreUser{
$dbhost = "localhost";
$dbname = "riskinarviointilomake";
$dbuser = "root";
$dbpass = "";
//private $email;
public function store($email){
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (!( $stmt = $conn->prepare("INSERT INTO users(unique_id,email, encrypted_password) VALUES(?,?,?)"))){
echo "Table creation failed: (" . $conn->errno . ") " . $conn->error;
}
$stmt->bind_param('sss', $unique_id,$email,$password);
$unique_id=123457764;
$password="df12467hh";
$result = $stmt->execute();
$stmt->close();
$conn->close();
}
}
<?php
include 'StoreTest.php';
if(isset($_GET['email'])){
$email = $_GET['email'];
$store = new StoreTest();
$store->store($email);
}
?>

how to convert mysqli_set_charset($conn,"utf8") into PDO format in MYSQL?

I trying to solve the UTF8 problem. So far i manage to test out and it works in mysqli connection.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tesddddt";
$conn = mysqli_connect($servername, $username, $password, $dbname);
mysqli_set_charset($conn,"utf8");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM customer";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["uid"]. " - Name: " . $row["username"]. " " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
I manage to Insert and Select data with characters shown in it's language format correctly with the above coding.
However, when I try to do it in PDO , it shows 1 error when I insert data.
public function __construct(){
try {
$conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user_name, $this->db_pass);
mysqli_set_charset($conn,"utf8"); // <- added here
$this->conn=$conn;
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
I got this error
Warning: mysqli_set_charset() expects parameter 1 to be mysqli, object given in...
My php project is using PDO and hence need to get this work in PDO format. Anyone know how to settle this?
You try to connect via PDO and then change the charset via mysqli, without having a mysqli connection, that is what's causing the warning.
In PDO the charset usually is being specified within the connection string, like this:
$conn = new PDO("mysql:host=yourhost;dbname=yourdbname;charset=utf8");

Wordpress theme functions not working when called

I have a wordpress site and I want to save and do the database connection in my functions.php
So I can be calling it in my templates.
Here are the functions code in the in functions.php
<?php
function dbconnd() {
$server = "localhost";
$duser = "wpuser";
$dpass = "wppass";
$dbname = "wpdb";
$conn = new mysqli($server, $duser,$dpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
?>
So in my main.php if I call dbconnd(); , it seems it's not working as it throws a fatal error as in the case below:
Fatal error: Call to a member function query() on a non-object in
/main.php on line 49
<?php
dbconnd();
$sql = "SELECT * FROM orderform WHERE status='last';";
$result = $conn->query($sql); //this is line 49
?>
But in case below when am not calling the function, it works perfectly
<?php
$server = "localhost";
$duser = "wpuser";
$dpass = "wppass";
$dbname = "wpdb";
$conn = new mysqli($server, $duser,$dpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM orderform WHERE status='last';";
$result = $conn->query($sql);
?>
The way you are doing right now, $conn is a local variable only inside the function. So you can't get the value outside the function that way.
The best solution would be this:
function dbconnd() {
$server = "localhost";
$duser = "wpuser";
$dpass = "wppass";
$dbname = "wpdb";
$conn = new mysqli($server, $duser,$dpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else
return $conn;
}
And then when you're going to call the function, run this:
$conn = dbconnd();
Also don't forget to include or require the functions.php file inside the php file calling it.

Why the require_once is not working in following scenario?

I've following code of a function in a PHP file titled sample.php :
function deleteValue($value) {
$servername = "localhost";
$username = "root";
$password = "jumbo";
$dbname = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "DELETE FROM user WHERE value = '$value'";
if ($conn->query($sql) === TRUE) {
$conn->close();
return true;
} else {
$conn->close();
return false;
}
}
Actually, in this file(sample.php) there are too many such functions which repeats the following database connectivity code :
$servername = "localhost";
$username = "root";
$password = "jumbo";
$dbname = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Then, I created one file titled db.php in the same folder and added the above code to it. Using require_once('db.php'); at the beginning of file 'sample.php'I included the file to the above code. Finally the code appeared as follows :
require_once('db.php');
function deleteValue($value) {
$sql = "DELETE FROM user WHERE value = '$value'";
if ($conn->query($sql) === TRUE) {
$conn->close();
return true;
} else {
$conn->close();
return false;
}
}
Now it's giving me 500 Internal Server error.
Even instead of including the file I tried by pasting the whole code from db.php at the beginning of file sample.php as follows but still I get 500 Internal Server Error.
$servername = "localhost";
$username = "root";
$password = "jumbo";
$dbname = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function deleteValue($value) {
$sql = "DELETE FROM user WHERE value = '$value'";
if ($conn->query($sql) === TRUE) {
$conn->close();
return true;
} else {
$conn->close();
return false;
}
}
Can someone please correct the mistake I'm making in my code?
Thanks in advance.
I will suggest you that in db_config.php file you should use only database config and functions like this:
$servername = "localhost";
$username = "root";
$password = "jumbo";
$dbname = "jumbo_jet";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
And in common.php use code like this:
require_once("db_config.php");
function deleteToken($receivedToken) {
global $conn;
$sql = "DELETE FROM user_login WHERE token = '$receivedToken'";
if ($conn->query($sql) === TRUE) {
return true;
}
return false;
}
I hope it will work for you. If anything else then let me know.

Categories