PHP connetion to mysql server database - php

I just want to test db connection from my browser. But i get empty page. I am not getting Error message.
<?php
$con = mysqli_connect('http://ec2-54-67-69-153.us-west-1.compute.amazonaws.com/', 'root', 'root') or die(mysqli_error($con));
if ($con) {
echo "success";
} else {
echo "fail";
}
mysqli_close($con);
?>

**Here is a handy function that connects you to a Database, using *Object Oriented* style:**
function MySQLi_quickConnect()
{
$host = 'somewebsite.db.120327161.hostedresource.com'; //or 'http://localhost'
$username = '<YOUR USERNAME>';
$password = '<YOUR PASSWORD>';
$database = '<YOUR DATABASES NAME>';
$db = new MySQLi($host,$username,$password,$database);
$error_message = $db->connect_error;
if($error_message != NULL){die("Error:" . $error_message . "<br>" . "Occured in function
MySQLi_quickConnect");}
return $db;
}
**A simple example on how you would query the Database:**
$db = MySQLi_quickConnect(); //this is your new Database object
$sql = "<YOUR SQL STATEMENT>";
$stmt = $db->query($sql);
if(!$stmt){die('MyError : ('. $db->errno .') '. $db->error);} //kill script, show errors

Related

Getting error Record updated successfully Fatal error: Uncaught Error: Call to a member function fetch_assoc() on array

<?php
getdata();
function getdata(){
$server="";
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * from items";
$result = mysql_query($query);
if(!$result) die("Oh crap...: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j <= $rows; $j++)
{
$row = mysql_fetch_row($result);
$row[1]= $server;
$command = "nslookup ".$server;
exec($command, $result);
$nslookup_result="";
foreach($result as $line){
$nslookup_result.= $line."<br> ";
}
updatenslookup($server,$nslookup_result);
}
$mysqli->close();
}
function updatenslookup($url,$nsresult) {
// Create connection
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
if ($mysqli->query($updatesql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
?>
This bit makes no sense to me:
function getdata(){
$server=""; //<---------- set here
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * from items";
$result = mysql_query($query);
if(!$result) die("Oh crap...: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j <= $rows; $j++)
{
$row = mysql_fetch_row($result);
$row[1]= $server; //<---- sure you want to do this
//your basically setting $row[1] = '' on every iteration
//so your command below is "nslookup " because $server = ''
$command = "nslookup ".$server;
exec($command, $result);
$nslookup_result="";
foreach($result as $line){
$nslookup_result.= $line."<br> ";
}
updatenslookup($server,$nslookup_result);
}
$mysqli->close();
}
It seems to me this bit $row[1]= $server; is backwards.
But lets not forget the SQLInjection issues here:
function updatenslookup($url,$nsresult) {
// Create connection
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
if ($mysqli->query($updatesql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
Specifically this stuff:
function updatenslookup($url,$nsresult) {
// ....
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
// ....
}
The big issue with it is I can inject whatever I want into this table, then you take that data and shoot it right into
exec("nslookup ".$row[1], $result); //simplified $server = $row[1] + exec("nslookup ".$server)
So in theory I can (or may be able to) inject my own command line calls into exec, at least to some extent. I'm not sure all what someone could do with these issues, what the worst case would be, but I would avoid it in any case.
There is no way for me to know where the data for updatenslookup($url,$nsresult) comes from or if its clean, but it doesn't matter. One reason to prepare the sql is to have the security right where the issue is so you can clearly tell by looking at just the query if its safe or not. And you don't have to worry about missing some piece of data that could sneak in there.
You should use escapeshellarg at the very least, and clean up the SQL vulnerabilities by preparing your queries.
As far as this Call to a member function fetch_assoc() on array, I don't even see a call to fetch_assoc() in your code. Maybe I missed it but all I see is this $row = mysql_fetch_row($result); for reading data, which is procedural where you use the OOP in the other code . which is irritating .. but I get it, which is why I only use PDO now...
Etc..
I always feel bad when I shred up someones hard work, but I would be remiss not to mention such a big security hole.
Cheers.

Sql Statement from PHP isnt inserting into Database but doesnt give an error

Thanks to this site i could manage to solve my problems, but my statement isnt going through on my database, but when i copy it and paste it directly to my database, it inserts without any problem. Here my code:
<?php
$ip = "***"; //MySQL Server IP
$user = "***"; //MySQL user
$pw = "***"; //MySQL password
$db = "***"; //Database
$sql_filter = "";
$con = mysqli_connect($ip, $user, $pw, $db);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
function register()
{
$username = $_POST[username];
$vorname = $_POST[vorname];
$nachname = $_POST[nachname];
$geschlecht = $_POST[geschlecht];
$geburtsdate = $_POST[geburtsdatum];
$password = $_POST[password];
$email = $_POST[email];
if($email!="" and $password!="" and $username!="" and $password==$_POST["password_confirm"])
{
$sql_filter = "INSERT INTO `tblUser`(`UserID`, `UserName`, `Vorname`, `Nachname`, `EMail`, `Geschlecht`,`Password`) VALUES ('','$username','$vorname','$nachname','$email','$geschlecht','$password')";
$_SESSION['filter'] = $sql_filter;
$page_query = mysqli_query($con, $_SESSION['filter']);
$page_nums = mysqli_num_rows($page_query);
//header('Location: index.php');
echo $sql_filter;
echo $_SESSION['filter'];
}
else
{
header('Location: 404.html');
}
}
if(isset($_POST['submit']))
{
register();
}
mysqli_close($con);
?>
I think the problem is your $con is undefined in the function register(). So add this in the beginning of your function :
function register()
{
global $con;
... // the rest of your function
}

I am trying to connect to a db

I am trying to connect to a db but I keep getting an error that pops up every chance I get to change the db or connection string . I am currently using php mysqli and wamp will not show any error with the connection itself .
calc.php:
class Login {
var $con;
function __construct($con){
$this->con = $con;
}
function try_connecting(){
$connecting = true;
if($connecting){
if(!$this->con){
die ("Could not connect") . $this->con->connect_errno;
} else {
echo "connected";
}
} else {
return $connecting;
}
}
function try_login(){
if(try_connecting()){
$q = "SELECT username, password FROM persons WHERE username = " . $_POST["username"] . " AND password = " . $_POST['pwd'];
$rows = $this->con->num_rows;
if($rows == 1){
echo "true";
} else {
echo "not user";
}
}
}
}
Here is the test.php:
<?php
include("calc.php");
$u = $_POST['username'];
$p = $_POST['pwd'];
$con = mysqli_connect("localhost","root","","rdb");
$form = new Login($con);
$form->try_connecting();
$form->try_login();
?>
connection string error Unknown database
You forgot to run this query
$q = "SELECT username, password FROM persons WHERE username = " . $_POST["username"] . " AND password = " . $_POST['pwd'];
$rows = $this->con->num_rows;
Try to add
$this->con->query($q)
between the lines above

How to connect to MySQL database in PHP using mysqli extension?

I have code like this to connect my server database:
<?php
$con = mysqli_connect("", "username", "password", "databasename");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
But it displayed "Failed to connect to MySQL", what is wrong with this code? First time I am trying it in web server, whereas my localhost worked perfectly.
mysqli_connect("","username" ,"password","databasename");//Server name cannot be NULL
use loaclhost for server name(In Loacl)
<?php
$con = mysqli_connect("localhost","username" ,"password","databasename");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Or can use MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$con = mysqli_connect($servername, $username, $password);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
EDIT 01
$servername = "localhost";
$username = "root";
$password = "";
To connect to the MySQL database using mysqli you need to execute 3 lines of code. You need to enable error reporting, create instance of mysqli class and set the correct charset.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'dbname', 3307);
$mysqli->set_charset('utf8mb4'); // always set the charset
The parameters in the mysqli constructor are all optional, but most of the time you would want to pass at least 4 of them. In the correct order they are:
MySQL Host. Most of the time it is localhost, but if you connect to a remote host it will be some other IP address. Make sure this does not contain the http protocol part. It should either be an IP address or the URL without protocol.
Username. This is the username of your MySQL user. To connect to the MySQL server you need to have a valid user with the right privileges.
Password.
Database name. This is the MySQL database name you want to connect to.
Port. Most of the time the default port is the correct one, but if you use for example wampserver with MariaDB, you might want to change it to 3307.
Socket name. Specifies the socket or named pipe that should be used.
Unfortunately the charset is not one of these parameters, so you must use a dedicated function to set this very important parameter.
Please beware never to display the connection errors manually. Doing so is completely unnecessary and it will leak your credentials.
On unrelated note: I do not recommend to use MySQLi in a new project. Please consider using PDO, which is overall a much better API for connecting to MySQL.
Why use mysqli? Just use PDO for safer mysql connection just use:
$hostname='localhost';
$username='root';
$password='';
$dbh = new PDO("mysql:host=$hostname;dbname=dbname",$username,$password);
You should specify hostname
$con = mysqli_connect("localhost","username" ,"password","databasename");
If it returns an error like
Failed to connect to MySQL: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'
Replace localhost with 127.0.0.1.
If still you cant connect check if mysql server is actually running.
service mysqld start
Then, try the one of the following following:
(if you have not set password for mysql)
mysql -u root
if you have set password already
mysql -u root -p
$localhost = "localhost";
$root = "root";
$password = "";
$con = mysql_connect($localhost,$root,$password) or die('Could not connect to database');
mysql_select_db("db_name",$con);
<?php
$servername="";
$username="";
$password="";
$db="";
$conn=mysqli_connect($servername,$username,$password,$db);
//mysql_select_db($db);
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno($conn) . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error($conn) . PHP_EOL;
exit;
}
#session_start();
$event_name = $_POST['first_name'];
$first_name = $_POST['last_name'];
$sql = "INSERT INTO customer(first_name, last_name,) VALUES ('$first_name', '$last_name')";
$conn->query($sql);
$lastInsertId = mysqli_insert_id($conn);
?>
A better method is to keep the connection and the login parameters apart.
<?php
class Database{
protected $url;
protected $user;
protected $passw;
protected $db;
protected $connection = null;
public function __construct($url,$user,$passw,$db){
$this->url = $url;
$this->user = $user;
$this->passw = $passw;
$this->db = $db;
}
public function __destruct() {
if ($this->connection != null) {
$this->closeConnection();
}
}
protected function makeConnection(){
//Make a connection
$this->connection = new mysqli($this->url,$this->user,$this->passw,$this->db);
if ($this->connection->connect_error) {
echo "FAIL:" . $this->connection->connect_error;
}
}
protected function closeConnection() {
//Close the DB connection
if ($this->connection != null) {
$this->connection->close();
$this->connection = null;
}
}
protected function cleanParameters($p) {
//prevent SQL injection
$result = $this->connection->real_escape_string($p);
return $result;
}
public function executeQuery($q, $params = null){
$this->makeConnection();
if ($params != null) {
$queryParts = preg_split("/\?/", $q);
if (count($queryParts) != count($params) + 1) {
return false;
}
$finalQuery = $queryParts[0];
for ($i = 0; $i < count($params); $i++) {
$finalQuery = $finalQuery . $this->cleanParameters($params[$i]) . $queryParts[$i + 1];
}
$q = $finalQuery;
}
$results = $this->connection->query($q);
return $results;
}
}?>
This in combination with a database factory keeps the data separated and clean.
<?php
include_once 'database/Database.php';
class DatabaseFactory {
private static $connection;
public static function getDatabase(){
if (self::$connection == null) {
$url = "URL";
$user = "LOGIN";
$passw = "PASSW";
$db = "DB NAME";
self::$connection = new Database($url, $user, $passw, $db);
}
return self::$connection;
}
}
?>
After that you can easily make your (class based) your CRUD classes (objectname+DB)
<?php
include_once "//CLASS";
include_once "//DatabaseFactory";
class CLASSDB
{
private static function getConnection(){
return DatabaseFactory::getDatabase();
}
public static function getById($Id){
$results = self::getConnection()->executeQuery("SELECT * from DB WHERE Id = '?'", array(Id));
if ($results){
$row = $results->fetch_array();
$obj = self::convertRowToObject($row);
return $obj;
} else {
return false;
}
}
public static function getAll(){
$query = 'SELECT * from DB';
$results = self::getConnection()->executeQuery($query);
$resultsArray = array();
for ($i = 0; $i < $results->num_rows; $i++){
$row = $results->fetch_array();
$obj = self::convertRowToObject($row);
$resultsArray[$i] = $obj;
}
return $resultsArray;
}
public static function getName($Id){
$results = self::getConnection()->executeQuery("SELECT column from DB WHERE Id = '?'", array($Id));
$row = $results->fetch_array();
return $row['column'];
}
public static function convertRowToObject($row){
return new CLASSNAME(
$row['prop'],
$row['prop'],
$row['prop'],
$row['prop']
);
}
public static function insert ($obj){
self::getConnection()->executeQuery("INSERT INTO DB VALUES (null, '?', '?', '?')",
array($obj->prop, $obj->prop, $obj->prop));
}
public static function update ($propToUpdate, $Id){
self::getConnection()->executeQuery("UPDATE User SET COLTOUPDATE = ? WHERE Id = ?",
array($propToUpdate, $Id));
}
}
And with this fine coding it's a piece of cake to select items in frontend:
include 'CLASSDB';
<php
$results = CLASSDB::getFunction();
foreach ($results as $class) {
?>
<li><?php echo $class->prop ?><li>
<php } ?>
The easiest way to connect to MySQL server using php.
$conn=new mysqli("localhost", "Username", "Password", "DbName");
if($conn->connect_error)
{
die("connection faild:".$conn->connect_error);
}
echo "Connection Successfully..!";
localhost like this (MySQLi Procedural)
<?php
$servername ="localhost";
$username="username";//username like (root)
$password="password";//your database no password. (" ")
$database="database";
$con=mysqli_connect($servername,$username,$password,$database);
if (!$con) {
die("Connection failed: " . MySQL_connect_error());
}
else{
echo "Connected successfully";
}

Using PHP in HTML to send object values to mysql database

I am creating a website where it sends values from a JavaScript object into a MySQL database via PHP
Here is the code:
<!DOCTYPE html>
<html>
<body>
<p>Creating a JavaScript Object.</p>
<p id="demo"></p>
<script>
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
</script>
</body>
</html>
Overall, my question is how to send the objects data to the MySQL using PHP?
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
If I type the code in before it prints out:
connect_error) {die("Connection failed: " . $conn->connect_error);} echo "Connected successfully";?>
It sounds to me like you are trying to jump from not knowing how to work with PHP and MySQL to also adding JavaScript.
First let me give you an example of how to work with all of those things.
Here is the repo with all of these files: https://github.com/Goddard/simplelogin-example.
This is what connects you to the database:
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
define("__DB_NAME__", 'job');
define("__DB_DSN__", 'mysql:dbname=' . __DB_NAME__ . ';host=127.0.0.1');
define("__DB_USERNAME__", 'root');
define("__DB_PASSWORD__", '');
if(session_id() == '') {
session_start();
}
if(!isset($_SESSION['username']))
{
$_SESSION['username'] = NULL;
}
//database setup
try {
$db = new PDO ( __DB_DSN__, __DB_USERNAME__, __DB_PASSWORD__ );
$db->query ( "use " . __DB_NAME__);
}
catch ( PDOException $e ) {
echo 'Could not connect : ' . $e->getMessage ();
}
?>
This is what works with the database information:
<?php
include("db.php");
if(trim(htmlentities(addslashes(filter_input(INPUT_GET, 'type')), ENT_QUOTES)) === "loginUser")
{
try {
$username = trim(filter_input(INPUT_GET, 'username'));
$password = trim(filter_input(INPUT_GET, 'password'));
$fetch = $db->prepare("SELECT * FROM `users` WHERE user_name = :username");
$fetch->bindParam(':username', $username, PDO::PARAM_STR);
$fetch->execute();
$result = $fetch->fetch(PDO::FETCH_OBJ);
if($result)
{
if(password_verify($password, $result->password_hash))
{
$currentDateTime = date('Y-m-d H:i:s');
$update = $db->prepare("UPDATE `users` SET `last_login` = :lastlogin WHERE `client_id` = :clientid");
$update->bindParam(':lastlogin', $currentDateTime);
$update->bindParam(':clientid', $result->client_id);
$loginUpdate = $update->execute();
$resultArray['error'] = 0;
$resultArray['errorMessage'] = "None";
$resultArray['userName'] = $result->user_name;
$_SESSION['username'] = $result->user_name;
echo json_encode($resultArray);
}
else
{
$resultArray['error'] = 1;
$resultArray['errorMessage'] = "Incorrect Password";
echo json_encode($resultArray);
}
}
else
{
$resultArray['error'] = 1;
$resultArray['errorMessage'] = "Incorrect Username";
echo json_encode($resultArray);
}
} catch (PDOException $e) {
$resultArray['error'] = 1;
$resultArray['errorMessage'] = $e->getMessage();
echo json_encode($resultArray);
}
}

Categories