Access denied for user 'unset_username'#'localhost' (using password: NO) - php

I have some PHP code that inserts data to MySQL database using MySQLi.
PHP code:
function insert_db($lat, $lng, $date, $user){
require('db_info_table.php');
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
return false;
}
$lat = mysql_real_escape_string($lat); // Sanitize data to prevent SQL injection
$lng = mysql_real_escape_string($lng);
$date = mysql_real_escape_string($date);
$user = mysql_real_escape_string($user); // << ERROR
$sql = "INSERT INTO table (lat, lng, date, user)
VALUES ('$lat', '$lng', '$date', '$user')";
if (mysqli_query($conn, $sql)) {
return true;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
return false;
}
mysqli_close($conn);
}
The connection details are located in a separate file in the same directory and it looks like this
$servername = "localhost";
$username = "user123";
$password = "pass123";
$dbname = "db123";
And I get these errors, I'm pretty sure one leads to another
mysql_real_escape_string(): Access denied for user 'unset_username'#'localhost' (using password: NO)
mysql_real_escape_string(): A link to the server could not be established in
And both errors appear on same line(look at the code).

It seems that you're connecting to server using mysqli library but then trying to use function from mysql library to secure you string. Use mysqli_real_escape_string() instead.
It basicaly doing the same thing as mysql_real_escape_string() but takes two params: first is connection link and second is variable that needs to be secured. So your code will look like this:
$lat = mysqli_real_escape_string($conn, $lat);
$lng = mysqli_real_escape_string($conn, $lng);
$date = mysqli_real_escape_string($conn, $date);
$user = mysqli_real_escape_string($conn, $user);

Related

Can't update arduino value to xampp database from link

I got the tutorial from this link
https://icreateproject.info/2014/12/14/arduino-save-data-to-database/
The tutorial is about how to save data from Arduino to xampp database over the local network.
I follow everything until step 3. This is the PHP code:
<?php
// Prepare variables for database connection
$dbusername = "arduino"; // enter database username, I used "arduino" in step 2.2
$dbpassword = "arduinotest"; // enter database password, I used "arduinotest" in step 2.2
$server = "localhost"; // IMPORTANT: if you are using XAMPP enter "localhost", but if you have an online website enter its address, ie."www.yourwebsite.com"
// Connect to your database
$dbconnect = mysql_pconnect($server, $dbusername, $dbpassword);
$dbselect = mysql_select_db("test",$dbconnect);
// Prepare the SQL statement
$sql = "INSERT INTO test.sensor (value) VALUES ('".$_GET["value"]."')";
// Execute SQL statement
mysql_query($sql);
?>
I tried to run this command in the link as mentioned in the tutorial
http://localhost/write_data.php?value=100
This is the error I get
Fatal error: Uncaught Error: Call to undefined function mysql_pconnect() in C:\xampp\htdocs\write_data.php:11 Stack trace: #0 {main} thrown in C:\xampp\htdocs\write_data.php on line 11
The mysql library that you are using is deprecated in php5.5
http://php.net/manual/en/function.mysql-connect.php
Here's an updated version with mysqli_connect
$dbusername = "arduino";
$dbpassword = "arduinotest";
$server = "localhost";
$database = 'test';
$mysqli = mysqli_connect($server, $dbusername, $dbpassword,$database);
// please validate the $_GET['value']
$sql = "INSERT INTO test.sensor (value) VALUES ('".$_GET["value"]."')";
mysqli_query($mysqli, $sql);
new mysqli http://php.net/manual/en/function.mysqli-connect.php
Somehow i managed to connect and changed the value by typing and auto insert using this code
<?php
header("Refresh:5");
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else {
echo "hello";
}
$value = $_GET['value'];
$sql = "INSERT INTO test.sensor (value) VALUES ($value)";
$sql = "INSERT INTO test.sensor (value)
VALUES ('255')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
And without this code, which is on line 28, i will get error so i have to put this code as well
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Thank you everyone for helping really appreciate it.

Inserting fields to MySQL Database through PHP not working

I am trying to insert values from gravity form submissions into mysql database using php, but nothing is showing up in my database when I try it:
Here is my code:
add_action("gform_after_submission_17", "push_fields", 10, 2);
function push_fields($entry, $form){
$title = $entry[1];
$location = $entry[1];
global $connection;
$query = ("INSERT INTO events(title, location) VALUES ($title, $location)");
$result = $connection->query($query);
}
I have already connected to the database, as I have used other functions that are pulling data already in the database:
$servername = '127.0.0.1';
$username = '*******';
$password = '*******';
$dbname = '*******';
$connection = new mysqli($servername, $username, $password, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
Please let me know if there is any other info you need.
EDITED (TO TEST FOR ERRORS):
add_action("gform_after_submission_17", "input_fields", 10, 2);
function add_entry($entry){
$title = mysql_real_escape_string($entry[1]);
$location = mysql_real_escape_string($entry[2]);
global $connection;
$query = ("INSERT INTO events(title, location) VALUES ('$title' , '$location')");
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
if($result){
echo 'Query OK';
}else{
echo 'Query failed';
}
}
This may be unhelpful if you're deliberately connecting to the DB; however, you might consider using the GFAPI.
https://docs.gravityforms.com/api-functions/#add-entry

Cant connect to MySQL, wrong code?

I have tried to connect to my db, but nothing works...
This is the code that I have created:
$name ='testdb';
$user = 'root';
$password = '';
$host = 'localhost';
$link = new mysqli($name, $user, $password, $host);
$name = $_POST['name'];
$message = $_POST['message'];
$mail = $_POST ['mail'];
$name = $link->real_escape_string($_POST['name']);
$message = $link->real_escape_string($_POST['message']);
$mail = $link->real_escape_string($_POST['mail']);
$sql = "INSERT INTO test (Name, Message, Mail) VALUES ('$name','$message', '$mail')";
$result = $link->query($sql);
I have allready double-checked all the spellings.
Can anyone give me some tips? I may have gone blind.
Seems you did not initialize mysqli connection properly
error_reporting(E_ALL);//display all errors
$name ='testdb';
$user = 'root';
$password = '';
$host = 'localhost';
$link = new mysqli($host, $user, $password, $name);
Use prepared statements(Prevents SQL injection)
$sql = "INSERT INTO test (Name, Message, Mail) VALUES (?,?,?)";//placeholders (3placeholders for 3values)
$statement = $link->prepare($sql);//prepare query. returns true/false
$statement->bind_param('sss',$name, $message, $mail);//you dont need to escape anymore
$statement->execute(); //execute safely
The first parameter of mysqli is the hostname, you swapped hostname and databasename Connect to MySQL
$link = new mysqli($host, $user, $password, $name);
You can also use prepared statement, to prevent SQL injections
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.
$sql = "INSERT INTO test (Name, Message, Mail) VALUES (?,? ?)";
$stmt = $link->prepare($sql);
$stmt->bind_param("sss",$name, $message, $mail);
$result = $stmt->execute();
if ($result) {
// query was successful
}else {
// query failure
}
Please use this below code it will help you
$name ='testdb';
$user = 'root';
$password = '';
$host = 'localhost';
$link = new mysqli($host,$user,$password,$name);
// Check connection
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
$name = $_POST['name'];
$message = $_POST['message'];
$mail = $_POST ['mail'];
$name = $link->real_escape_string($_POST['name']);
$message = $link->real_escape_string($_POST['message']);
$mail = $link->real_escape_string($_POST['mail']);
$sql = "INSERT INTO test (Name, Message, Mail) VALUES ('$name','$message', '$mail')";
if ($link->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $link->error;
}
$link->close();
To learn basic things in PHP and MYSQL refer this link
https://www.w3schools.com/php/

Cant insert specific row into the database PHP MySQL JSON

I pulled the json into the php object and started putting data from that object into the database. I have 20 users in json and everyone succeded to go into the database except one which surname is O'Carolan. I think that error is in that single quote, smth about that. I read everything about sql injection and tried everything i found here on stackoverflow with the similar errors and still doesnt work. I tried with the PDO also and prepared statements and still doesnt work. Here I always get an error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' 'male')' at line 2. Also, when printing out the users from json it prints them properly and everything is ok there, just that 3rd user O'carolan wont go into to database.
My json is at http://dev.30hills.com/data.json and my code is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "30hills";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$json_string = 'http://dev.30hills.com/data.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, false);
$elementCount = count($obj);
for ($x = 0; $x < $elementCount; $x++) {
$id = $obj[$x]->id;
$firstname = $obj[$x]->firstName;
$surname = $obj[$x]->surname;
//if (preg_match('/'.$special_chars.'/', $surname)){
// $surname = str_replace("'","",$surname);
//}
$age = $obj[$x]->age;
$gender = $obj[$x]->gender;
echo $id;
echo " ";
echo $firstname;
echo " ";
echo $surname;
echo "<br>";
mysqli_query($conn, "INSERT INTO user (`id`, `firstName`, `surname`, `age`, `gender`)
VALUES($id, '$firstname', '" . $surname . "', $age, '$gender')")
or die(mysqli_error($conn));
?>
The answer is that age = null in json wont insert into database, must make that nullable into the table

MYSQL AES_ENCRYPT issues

I have a simple application that needs to store sensitive data in a Wordpress installation.
The data comes from the user via a Form, and up until now, I have been storing the data using $wpdb->insert, however as we get closer to launching this project, I want to make sure that sensitive user information is encrypted, and only decrypted when read.
I have no clue how to make this work using the $wpdb class, so I resorted to using mysqli for this component. So far, I run the $wpdb->insert statement to insert all the normal data, then open a new connection to try and insert the sensitive data.
$id = $wpdb->insert_id;
$servername = 'localhost';
$username = 'root';
$password = 'root';
$db = 'wp_database';
$conn = new mysqli( $servername, $username, $password, $db );
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch Data and store it
$sud = $form['sens_user_data'];
$key = 'mysecretkey';
$tbl = $wpdb->prefix . 'sensitive';
$sql = "UPDATE $tbl SET sens_user_data = AES_ENCRYPT(?, ?) WHERE id = ?";
if ( $stmt = $conn->prepare($sql) ) {
$stmt->bind_param('ssi', $sud, $key, $id);
$stmt->execute();
} else {
$error = $conn->errno . ' ' . $conn->error;
ChromePhp::log($error);
}
$conn->close();
This appears to work correctly, except all the values always encode to a single character, and then decode to NULL
What am I doing wrong?

Categories