could anyone please help me find what exactly the error is? - php

Connection failed: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known.
( ! ) Fatal error: Uncaught Error: Call to a member function prepare() on string in C:\wamp\www\websits\admin\validate.php on line 17
( ! ) Error: Call to a member function prepare() on string in C:\wamp\www\websits\admin\validate.php on line 17
Code-
<?php
include_once('connection.php');
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"]== "POST") {
$adminname = test_input($_POST["adminname"]);
$password = test_input($_POST["password"]);
$stmt = $conn->prepare("SELECT * FROM adminlogin");
$stmt->execute();
$users = $stmt->fetchAll();
foreach($users as $user) {
if(($user['adminname'] == $adminname) &&
($user['password'] == $password)) {
header("Location: adminpage.php");
}
else {
echo "<script language='javascript'>";
echo "alert('WRONG INFORMATION')";
echo "</script>";
die();
}
}
}
?>
// Connection -
<?php
$conn= "";
try {
$servername = "localhost:3306";
$dbname = "website";
$username = "root";
$password = "";
$conn = new PDO("mysql:host=$servername and dbname=website",$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>

Check Your connection.php file is it in the same directory where validate.php file is if not them provide the correct path, else your prepare statement is correct.
Where is you Connection file is can you share the path of of connection.php and validate.php path.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_db_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

Your connection string is wrong
Your string
$conn = new PDO("mysql:host=$servername and dbname=website",$username, $password);
Should be
$conn = new PDO("mysql:host={$servername};dbname={$dbname}",$username, $password);
And your servername should be without a port
$servername = "localhost";
Please see
https://www.php.net/manual/en/pdo.connections.php

Alter your connection.php code as follows,
$username = 'root';
$password = '';
$conn = new PDO('mysql:host=localhost;dbname=website',$db_username,$db_password );
if(!$conn){
die("Fatal Error: Connection Failed!");
}

Related

Cant perform an SQL update when using php varibles

I just noticed that i can not perform SQL updates when i am using PHP varibles from the link
My code (I don't noticed any errors, and no error output)
<?php
if ($_POST && isset($_POST['hdduid'], $_POST['status'])) {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'L24wmc1nJBVP90q9yY';
$dbname = 'watt';
try {
// Try to connect
$dbh = new PDO(
'mysql:host='.$dbhost.';dbname='.$dbname,
$dbuser,
$dbpass
);
// Data
$hdduid = $_POST['hdduid'];
$status = $_POST['status'];
// query
$sql = "UPDATE users SET paid=':status' WHERE hdduid=':hdduid'";
$q = $dbh->prepare($sql);
$q->execute(array(
':message' => $message,
':email' => $email
));
// Null connection
$dbh = null;
} catch (PDOException $e) { // if exception
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
I edited the code, it still wont working
You need to use
mysqli_real_escape_string
Not
mysql_real_escape_string
You can not mix mysql with MySQLi
Here is another solution using prepared statements.
$servername = "localhost";
$username = "root";
$password = "L24wmc1nJBVP90q9yY";
$dbname = "ft";
// Create connection
$connection = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$paid = $_GET["status"];
$hdduid = $_GET["hdduid"];
//Prepared statements
$statement = $connection->prepare("UPDATE users SET paid = ? WHERE hdduid = ?");
$statement->bind_param("ss", $paid, $hdduid);
if(!$statement->execute()) {
echo "Error updating record: " . $statement->error;
} else {
echo "Record updated successfully";
}
$statement->close();
$connection->close();
Here is a solution. It uses mysqli_real_escape_string instead of mysql_real_escape_string. I also changed the name of $status to $paid for better readability. Good luck!
$servername = "localhost";
$username = "root";
$password = ""; //$password = "L24wmc1nJBVP90q9yY";
$dbname = "test"; //$dbname = "ft";
// Create connection
$connection = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$hdduid = $_GET["hdduid"];
$paid = $_GET["status"];
$sql = "UPDATE users SET paid='$paid' WHERE hdduid='$hdduid'";
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $connection->error;
}
$connection->close();

PHP connection and query error: Fatal error: Call to a member function query() on null in

I'm getting the above error in regards to my statement below, tried multiple fixes from other answers in stack but continue to get the same error :(
this is part of a php code in a user registration form, would like their info to insert in the table
if($conn->query( "INSERT INTO users (FIRST_NAME, LAST_NAME, USERNAME, PASSWORD)
VALUES ('$fname', '$lname', '$uname', '$pword')")==TRUE){
echo 'Inserted';
}else{
echo 'Not Inserted';
}
i have this other code in a separate file for the $conn
function dbConnect(){
$servername = "x";
$database = "activity2";
$username = "root";
$password = "root";
// Create connection
$conn = new
mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);
} //echo "Connection successful"; //make variable global to access in other
functions global $conn; return $conn;}
First thing to do is to create the class that will return a connection:
<?php
//filename: dbConnect.php
class dbConnect
{
public function connect() {
global $conn;
$servername = "localhost";
$username = "root";
$password = "";
$database = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} //echo "Connection successful"; //make variable global to access in other
return $conn;
}
}
?>
Now you can execute your sql command in another file:
<?php
require 'dbConnect.php';
$db = new dbConnect();
$conn = $db->connect();
$nome = "Anailton";
$email = "jose#hotmail.com";
if($conn->query( "INSERT INTO clientes (NOME, EMAIL) VALUES ('$nome', '$email')")==TRUE){
echo 'Inserted';
}else{
echo 'Not Inserted';
}
?>

php mysql connection get error message

this is my first php code , i am trying to connect to a database with user name = "root" and password = "root"
i have a connection file called dbConnection.php
as following :
<?php
echo "in connection file";
$hostname = "localhost";
$username = "root";
$password = "root";
$db = "ledDB";
echo "<br> db-connection : vars definde ";
//connection to the database
$conn = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
echo "db-connection : initilize connection ";
mysql_select_db($db);
echo "db-connection : connection done";
// Check connection
echo "Connected successfully";
?>
and i call it in a file called what.php :
<?php
echo "Hello";
include "dbConnection.php";
echo "ohhhh";
?>
this returns status code 500 which is internal server error
but i want to know what is the error to fix it how can i get the error message ?
i tried
$conn = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
but it is not returning any thing.
can any one help me please ?
if you are having password on localhost then use password otherwise leave it blank
$con = mysqli_connect("localhost","root","yourpassword","yourdb");
You mysqli_connect() method.
<?php
echo "in connection file";
$hostname = "localhost";
$username = "root";
$password = "root";
$db = "ledDB";
echo "<br> db-connection : vars definde ";
//connection to the database
$conn = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
echo "db-connection : initilize connection ";
mysqli_select_db($conn,$db);
echo "db-connection : connection done";
// Check connection
echo "Connected successfully";
?>
First Thing is to Change your connection method to mysqli or my personal favorite PDO.
PDO Example:
class db extends pdo{
//Website Variables
public $sitedb = '';
public $siteconfig;
public $sitesettings = array(
'host' => 'localhost',
'database' => 'yourdb',
'username' => 'youruser',
'password' => 'yourpass',
);
public function __construct(){
$this->sitedb = new PDO(
"mysql:host={$this->sitesettings['host']};" .
"dbname={$this->sitesettings['database']};" .
"charset=utf8",
"{$this->sitesettings['username']}",
"{$this->sitesettings['password']}"
);
$this->sitedb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
}
$db = new db();
Then you can extend your PDO class to new classes after including the db.php page.
Example Select:
class yourclass extends db {
public function SelectUsers() {
global $db;
$query = <<<SQL
SELECT email
FROM users
WHERE active = :active
SQL;
$resource = $db->sitedb->prepare( $query );
$resource->execute( array (
':active' => 1,
));
$count = $resource->rowCount();
foreach($resource as $user){
$this->email = $user['email'];
}
}
}
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydb";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
// make the current db
$db_selected = mysqli_select_db ( $conn , $dbname );
if (!$db_selected) {
die ('Can\'t connect to Database : ' . mysql_error());
}
?>

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.

MySQLi Query not Returning Results properly

I'm trying to switch my website over to MySQLi and I'm following the W3schools MySQLi guide to do so. I've hit a roadblock, though. I have a function to check if a specified user is an admin on the site. I've put echo in various spots to find where the issue is, and I've figured out that it most likely doesn't see the user. $username is set to the variable $user. Here's the whole code block (part of connect.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lark";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
session_start();
if(!isset($_SESSION["user_login"])) {
$user = "";
} else {
$user = $_SESSION["user_login"];
}
//functions
function isAdmin($username) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lark";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_get_is_admin = "SELECT * FROM users WHERE username='$username' LIMIT 1";
$get_is_admin = mysqli_query($conn, $sql_get_is_admin);
if(mysqli_num_rows($get_is_admin) > 0) {
echo "num_rows";
while ($row = mysqli_fetch_assoc($get_is_admin)) {
$is_admin_bool = $row['admin'];
echo "while";
if($is_admin_bool == 0){
return false;
} elseif ($is_admin_bool == 1) {
return true;
}
}
} else {
echo "not found.";
}
}
?>
Here's the code I used to test the $user variable:
<?php
include("connect.php");
?>
<div class="main">
<h1>Welcome back, <?php echo $user; ?></h1>
foo
<?php
/*if(isAdmin($user) == true) {
echo "<div style='display: table-cell;' class='rightcell'>
<h3 style='color: #000;'>Admin Tools</h3>
<a href='userlist.php' target='_blank'>Userlist</a>
</div>";
} else {
} */
echo isAdmin($user);
?>
</div>
I also had to reconnect to the database or else I'd get this error on the site:
Notice: Undefined variable: conn in C:\xampp\htdocs\lark\connect.php on line 33
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\lark\connect.php on line 33
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\lark\connect.php on line 35 not found.
If I fix it so there's no error, it just says "not found."
the $conn variable is not defined in your function, example:
function isAdmin($username) {
global $conn;
..................
}
You don't have $conn in your function, it is commented out.
function isAdmin($username) {
/*$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lark";
$conn = mysqli_connect($servername, $username, $password, $dbname);*/

Categories