Unable to connect to MY SQL DB in Ajax call using PHP - php

I am performing a DB operation after making an ajax call using php,
1) I see in fiddler that the request and response to the PHP (ajax call) are fine but and 2) I see the error "Access denied for user 'root'#'localhost' (using password: NO" in Fiddler.
I am not trying to connect to root but to a different user.
Here is the view.php file where ajax call is initiated:
$.ajax({
url: 'delete_entry.php',
data: "id="+del_id,
type: 'post',
success: function(output) {
alert("Success");
//document.getElementById("test1").innerHTML = output;
}
});
I recieve the alert message "Success" though.
Code in delete_entry.php:
<?php
$servername = "localhost";
$username = "testdb";
$password = "testdb";
$dbname = "testts";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo "Connection Failed";
die("Connection failed: " . $conn->connect_error);
}
$id=$_POST['id'];
echo $id; // I get a proper Id here
$delete = "DELETE FROM ExpenseTable WHERE Id='"+$id+"'";
$result = mysql_query($delete) or die(mysql_error());
?>
Please help as I do not understand why the mysql db is trying to connect to root eventhough I specify the db detais as "testdb".
I am able to connect to the same db with these credentials in my view.php

You are not using your created DB connection when you pass the sql query to the DB. Use the mysqli_query method as below..
mysqli_query($conn,$delete);

Related

Which username/password do I use to connect to mySQL

So, I'm SUPER new to mySQL. Having issues connecting to my database with PHP. Hoping someone can point me in the right direction.
I can login to our Cpanel using my username/password. Using the web gui I was able to create a database.
Now when I try to connect to the database (or even just the server for that matter) using PHP I get an error:
Warning: mysqli::__construct(): (HY000/1045): Access denied for user 'username'#'servername' (using password: YES) in /home/ropepart/public_html/techportal/sandbox/mysqltest.php on line 8
Connection failed: Access denied for user 'username'#'servername' (using password: YES)
To me, it seems like this is a username/password error. But I an using the same username/password that I use to login to the web gui. Why can I successfully login there, but can't login with PHP?
Here's my code (taken pretty much directly from W3Schools):
<?php
$servername = "servername";
$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";
?>
(Hopefully it's obvious that I've changed my servername/username/password for the purposes of this post)
Check the details correctly, By deafult
host = localhost
username = root
password = (No password leave it as empty)
database = (your database)
<?php
$connection = new mysqli('host','username','password','your_database');
if($connection->connect_error || $connection->error){
echo "error";
}else{
echo "done";
}
?>
you should add database name.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "demo"
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
//if you are using xampp you shoul locate this file you get information from this
passwords.txt
MySQL database username/password is not necessarily same as cPanel username & password.
Here is what you should do:
Login to your cPanel
From dashboard click "MySQL® Databases"
Add a new user from there (https://prnt.sc/kpiby9). Just fill username
and password (note down the password).
Add that user with your database by selecting both from the dropdown
(https://prnt.sc/kpidqx)
Now, use this username & password to connect with the database.
mysqli_connect(serverhostname,username,password,dbname);

Why isn't the response from Ajax showing?

I'm passing values using ajax from a web page to a php file. The purpose is to pass database credentials to be able to test the database connection and get the result in return. I'm passing server name, username and password to the php file. The problem is that I'm not able to see the database connection response from the php file.
This is how I call the function within document ready:
$('#dbconn').click(db_connect)
Here is my ajax code:
function db_connect(dbserver, dbuser, dbpassword) {
var dbserver;
var dbuser;
var dbpassword;
dbserver = $('input:dbserver').val();
dbuser = $('input:dbuser').val();
dbpassword = $('input:dbpassword').val();
$.ajax({
url : "script/create_db.php",
type : "POST",
cache : false,
data : {
dbserver : dbserver,
dbuser : dbuser,
dbpassword: dbpassword,
success: function(result){alert ("response")}
}
});
};
And this is my php code:
$servername = $_GET["dbserver"];
$username = $_GET["dbuser"];
$password = $_GET["dbpassword"];
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else{
echo "Connection succsess";
}
Any help is highly appreciated
success: function(result){alert ("response")}
When you get the response you alert the string "response".
You ignore the value of result entirely.
You don't see the response because you aren't looking for it.

Create connect.php with require at .htx file

"add.htx"
<?php
$servername = "my_server_name";
$username = "my_username";
$password = "my_pwd";
$dbname = "my_db_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Drama_Gr (Date, Time, Cont, Temp, Hum, Pres, Rain_Y, Rain_M, Rain, Rain_Rate, Wind, Wind_Dir)
VALUES ('<!--date-->', '<!--time-->', '<!--ForecastStr--> frc', '<!--outsideTemp-->', '<!--outsideHumidity-->', '<!--barometer-->', '<!--totalRain-->', '<!--monthlyRain-->', '<!--dailyRain-->', '<!--rainRate-->', '<!--windSpeed-->', '<!--windDirection-->bfr')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
run this file with weatherlink
and output the result file
"add.php"
<?php
$servername = "my_server_name";
$username = "my_username";
$password = "my_pwd";
$dbname = "my_db_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Drama_Gr (Date, Time, Cont, Temp, Hum, Pres, Rain_Y, Rain_M, Rain, Rain_Rate, Wind, Wind_Dir)
VALUES ('17/08/16', ' 0:11', ' Increasing clouds with little temperature change. frc', '24.6', '52', '1012.6', '291.2', '11.2', '0.0', '0.0', '1.6', 'SSEbfr')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
its ok with this way i create a database with my weather station
the problem is i want to give this code to run with weather station and other people from my area and create in to my database tables from other weather station but i don't want to include this code my database connection.
i think the correct way is to create a file like
"connect.php"
<?php
$servername = "my_server_name";
$username = "my_username";
$password = "my_pwd";
$dbname = "my_db_name";
mysql_connect($hostname, $username, $password) OR DIE("Unable to connect to database! Please try again later.");
mysql_select_db($dbname);
?>
and call this file like
<?php include("connect.php");?>
i try to add this code in "add.htx"
but get bellow error in "add.php"
Connection failed: Access denied for user ''#'localhost' (using password: NO)
why? maybe i think because the file "add.htx" start from weatherlink by local C:\WeatherLink\ but the weatherlink upload this file and convert to "add.php" at server at folder like http://my_website/weather/ ,this folder also include and the file "connect.php"
please any help
and if is easy give me the correct code at "add.htx" with the wright way to add at "add.htx"
<?php include("connect.php");?>
thanks
Was this what you did?
<?php
Include('connect.php');
$servername = "my_server_name";
$username = "my_username";
$password = "my_pwd";
$dbname = "my_db_name";
......
?>
Php is not running your include('connect. Php') file.
Bt then, I think the problem is not with the code. I think the problem is with your privileges. Compare ur server username and password with the ones you defined in your script.
// Connection failed: Access denied for user ''#'localhost' (using password: NO)// pls do check ur privileges
for other people i give the solution
first thanks to Script47 (open my eyes and see mysql_* must change to mysqli_*)
second i create i think the better way to call
"config.php"
here the fresh change at code "add.htx"
<?php
include("config.php");
include("opendb.php");
$sql = "INSERT INTO Drama_Gr (Date, Time, Cont, Temp, Hum, Pres, Rain_Y, Rain_M, Rain, Rain_Rate, Wind, Wind_Dir)
VALUES ('<!--date-->', '<!--time-->', '<!--ForecastStr--> frc', '<!--outsideTemp-->', '<!--outsideHumidity-->', '<!--barometer-->', '<!--totalRain-->', '<!--monthlyRain-->', '<!--dailyRain-->', '<!--rainRate-->', '<!--windSpeed-->', '<!--windDirection-->bfr')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
include("closedb.php");
?>
i create 3 files
to connect with db and close the db
"config.php"
<?php
$servername = "my_host_name";
$username = "my_username";
$password = "my_pwd";
$dbname = "_my_database_name";
?>
after i create a script
"opendb.php"
<?php
// Create my Weather db connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check my Weather db connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
and i think is correct to create and script to close a connection when upload data to db ,name this script
"closedb.php"
<?php
// close my weather db connection
mysqli_close($conn);
?>
and finally the result to
"add.php"
New record created successfully
thanks and i hope this usefull and for others
now the last problem is with this code "add.php" the records update the db rows when refresh this page
i create a below script to auto refresh multiple files from weather stations in one page but must this page is open to auto update the new result to db and name this page
"send_db.html"
<html>
<head>
<!-- For ease i'm just using a JQuery version hosted by JQuery- you can download any version and link to it locally -->
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$("#responsecontainer").load("http://www.dramaweather.gr/weather2/uploadwl/mysql/add.php");
var refreshId = setInterval(function() {
$("#responsecontainer").load('http://www.dramaweather.gr/weather2/uploadwl/mysql/add.php?randval='+ Math.random());
}, 900000);
$.ajaxSetup({ cache: false });
});
</script>
<script>
$(document).ready(function() {
$("#responsecontainer").load("http://www.dramaweather.gr/weather2/uploadwl/mysql/add_Serres.php");
var refreshId = setInterval(function() {
$("#responsecontainer").load('http://www.dramaweather.gr/weather2/uploadwl/mysql/add_serres.php?randval='+ Math.random());
}, 900000);
$.ajaxSetup({ cache: false });
});
</script>
</head>
<body>
<div id="responsecontainer">
</div>
</body>
</html>
is any other way to send the results of "'add.htx" to db auto every 10 minutes without a code from "send_db.html"
;
thanks again for the first problem if anyone know and my for my second problem the solution please help

*Beginner* Connecting MAMP to phpMyAdmin for an SQL database of forms created in HTML/alternative?

I'm currently trying to connect a PHP file in MAMP to an SQL database table already created under phpMyAdmin via Bluehost. One issue that comes across are two errors that occur when opening the databse.php file as HTML:
Warning: mysqli_connect(): (HY000/1045): Access denied for user 'root'#'localhost' (using password: YES) in /Users/*******/Desktop/Local Host/webpage#2/database.php on line 8.
Warning: mysqli_query() expects parameter 1 to be mysqli, boolean given in /Users/*******/Desktop/Local Host/webpage#2/database.php on line 13.
Once this is connected to my MAMP how do I connect to phpMyAdmin or is there a preferred route using only my Bluehost account.
I'm currently trying to create a database for forms using HTML->PHP->sql. The PHP file that collects the database info is fine and my "database.php" w/ errors is:
<?php
$host='localhost';
$user='root';
$pass='root';
$db='mdonnerm_sfddb';
$con=mysqli_connect($host,$user,$pass,$db);
if($con)
echo 'connected succefully to mydb database';
$sql="insert into form (Name, Gender, Email, Comment) values ('flankh', 'flank#gmail.com', 'male', 'hello world')";
$query=mysqli_query($con,$sql);
if($query)
echo 'data inserted succefully';
?>
Is there an alternative that is used to connecting HTML forms to PHP (processing AND database PHP files required or just an individual file) to SQL?
Also, is there a way to use a single PHP file for multiple form entries or does each form require a new processing PHP file?
change your code to
$host='localhost';
$user='root';
$pass='root';
$db='mdonnerm_sfddb';
$conn = mysqli_connect($host, $root, $pass, $db);
if (!$conn) {
die('Could not connect: ' . mysqli_error());
}
else
echo 'Connected successfully';
$sql="insert into form (Name, Gender, Email, Comment) values ('flankh', 'flank#gmail.com', 'male', 'hello world')";
$query=mysqli_query($con,$sql);
if($query)
echo 'data inserted succefully';
else
{
echo "ERROR: Could not able to execute $query. " . mysqli_error($con);
}
or use object oriented method for mysqli
$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);
}

On PHP, about using mysql or mysqli

I'm running MySQL server version 5.0.77 on Linux (Rocks Cluster Distro), and I'm trying to connect to the same database with both MySQL and MySQLi PHP functions. The problem is that when the MySQLi code fragment is executed it does work, but the MySQL fragment doesn't (in case it matters; not even on separate PHP files).
As shown in the code below I'm attempting a connection to the same database on the same host, using the same user and password but the MySQL function version fails.
(If it helps I've already tried the same code on MySQL server 5.6.20 running in Windows with the same details ((local)host, database, user, password) and both functions work).
What might be the problem? Any help is appreciated.
The output and code fragment is the following:
Code:
<?PHP
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tedDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Error [mysqli]: ".$conn->connect_error);
} else {
echo "Success [mysqli]";
}
echo "<br><br>";
$link = mysql_connect($servername, $username, $password)
or die("Error [mysql_connect]: ".mysql_error());
echo "Success [mysql_connect]";
?>
Output (LINUX):
Success [mysqli]
Error: Access denied for user 'root'#'localhost' (using password: NO)
Output (Windows):
Success [mysqli]
Success [mysql_connect]

Categories