escape-data mysqli function wont work - php

I am trying to move from mysql to mysqli. I am connecting fine and simple queries seem to work. However, I want an escape_date function and it keeps tell me that
Notice: Undefined variable: conn in $data =
mysqli_real_escape_string($conn, $data);
here's my code. The function is called when the form data is being processed.
ini_set('display_errors',1);
error_reporting(E_ALL);
// connect to the database
$servername = "localhost";
$username = xxx;
$password = xxx;
$dbname = xxx;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo '<p>you are connected</p>';
}
// escaping data function
function escape_data($data){
// address magic quotes
if (ini_get('magic_quotes_gpc')){
$data = stripslashes($data);
}
$data = mysqli_real_escape_string($conn, $data);
//return the escaped value
return $data;
}

You got $conn nowhere within scope of escape_data(). Pass it as argument

Related

Showing Error in a php function

I have declared a function called test_input in my php script,which working absolutely fine in another scripts.
It shows error
Fatal error: Uncaught Error: Call to undefined function test_input() in C:\xampp\htdocs\submitdata\cwisubmit.php:25 Stack trace: #0 {main} thrown in C:\xampp\htdocs\submitdata\cwisubmit.php on line 25
My php script is:
<?php
$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);
}
echo "Database Connected SUCCESSFULLY";
if($_SERVER["REQUEST_METHOD"]=="POST") {
// Variables initialization
$fname=$lname=$dob=$phone=$email=$postcode=$staddress=$city=$lan=$lcwi=$ptype=$mhtype="";
// Retrieving the data from the form
$fname=test_input(mysqli_real_escape_string($conn,$_POST['fname']));
$lname=test_input(mysqli_real_escape_string($conn,$_POST['lname']));
$dob=test_input(mysqli_real_escape_string($conn,$_POST['dob']));
$phone=test_input(mysqli_real_escape_string($conn,$_POST['phone']));
$email=test_input(mysqli_real_escape_string($conn,$_POST['email']));
$postcode=test_input(mysqli_real_escape_string($conn,$_POST['postcode']));
$staddress=test_input(mysqli_real_escape_string($conn,$_POST['staddress']));
$city=test_input(mysqli_real_escape_string($conn,$_POST['city']));
$lan=test_input(mysqli_real_escape_string($conn,$_POST['lan']));
$lcwi=test_input(mysqli_real_escape_string($conn,$_POST['lcwi']));
$ptype=test_input(mysqli_real_escape_string($conn,$_POST['ptype']));
$mhtype=test_input(mysqli_real_escape_string($conn,$_POST['mhtype']));
function test_input($data) {
$data=trim($data);
$data=stripslashes($data);
return $data;
}
//sql insert
$sql="INSERT INTO cwi(fname, lname, dob, phone, email, postcode, staddress, city, lan, lcwi, ptype, mhtype) VALUES('$fname','$lname','$dob','$phone','$email','$postcode','$staddress','$city','$lan','$lcwi','$ptype','$mhtype')";
if($conn->query($sql)===TRUE){
echo "<center>RECORDS UPDATED SUCCESSFULLY</center>";
}else{
echo "Error: ".$sql."<br>".$conn->error;
}
}
$conn->close();
?>
Please check this code whether there is error in my code or why its returning this error
PHP functions can be called before defining it because PHP parses the file first and then executes it. But here is the twist.
Functions that are enclosed in a conditional statement(if else) will
not be parsed. It will be only available after PHP interprets if
So, You have to move your function outside of IF block like
if(condition){
//your code
}
//Your function
function test_input($data){
$data=trim($data);
$data=stripslashes($data);
return $data;
}
define your test_input() function outside of
if($_SERVER["REQUEST_METHOD"]=="POST"){
and your code
if($_SERVER["REQUEST_METHOD"]=="POST"){
seems miss "}"
Changes are made to the code try this. It should work fine.
<?php
$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);
}
echo "Database Connected SUCCESSFULLY";
if($_SERVER["REQUEST_METHOD"]=="POST"){
//Variables initaition
$fname=$lname=$dob=$phone=$email=$postcode=$staddress=$city=$lan=$lcwi=$ptype=$mhtype="";
//Retrieving the data from the form
$fname=test_input(mysqli_real_escape_string($conn,$_POST['fname']));
$lname=test_input(mysqli_real_escape_string($conn,$_POST['lname']));
$dob=test_input(mysqli_real_escape_string($conn,$_POST['dob']));
$phone=test_input(mysqli_real_escape_string($conn,$_POST['phone']));
$email=test_input(mysqli_real_escape_string($conn,$_POST['email']));
$postcode=test_input(mysqli_real_escape_string($conn,$_POST['postcode']));
$staddress=test_input(mysqli_real_escape_string($conn,$_POST['staddress']));
$city=test_input(mysqli_real_escape_string($conn,$_POST['city']));
$lan=test_input(mysqli_real_escape_string($conn,$_POST['lan']));
$lcwi=test_input(mysqli_real_escape_string($conn,$_POST['lcwi']));
$ptype=test_input(mysqli_real_escape_string($conn,$_POST['ptype']));
$mhtype=test_input(mysqli_real_escape_string($conn,$_POST['mhtype']));
//sql insert
$sql="INSERT INTO cwi(fname, lname, dob, phone, email, postcode, staddress, city, lan, lcwi, ptype, mhtype) VALUES('$fname','$lname','$dob','$phone','$email','$postcode','$staddress','$city','$lan','$lcwi','$ptype','$mhtype')";
if($conn->query($sql)===TRUE){
echo "<center>RECORDS UPDATED SUCCESSFULLY</center>";
}else{
echo "Error: ".$sql."<br>".$conn->error;
}
}
$conn->close();
function test_input($data)
{
$data=trim($data);
$data=stripslashes($data);
return $data;
}
?>

Call MySQL stored procedure from PHP

I have looked at several examples on how to call a MySQL stored procedure from PHP but none have helped me. The stored procedure works when run inside PHPMyAdmin but I am having trouble calling it from the web.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn,"CALL standings_build()");
if (mysqli_query($conn,$sql))
header('refresh:1; url=schedule_main_scores.php');
else
echo "failed";
?>
There's 2 problems here.
You're querying twice and using the wrong variable, being $sql instead of $result.
$result = mysqli_query($conn,"CALL standings_build()");
if (mysqli_query($conn,$sql))
^^^^^^^^^^^^ calling the query twice
^^^^ wrong variable, undefined
all that needs to be done is this:
if ($result)
and an else to handle the (possible) errors.
Error reporting and mysqli_error($conn) would have been your true friends.
http://php.net/manual/en/function.error-reporting.php
http://php.net/mysqli_error
Side note: You really should use proper bracing techniques though, such as:
if ($result){
echo "Success";
}
else {
echo "The query failed because of: " . mysqli_error($conn);
}
It helps during coding also and with an editor for pair matching.

How do I hide the echo result from showing up on HTML?

For Instance consider this standard database connection php file.
db_conn.php
<?php
$servername = "localhost";
$username = "root";
$password = "Yash123";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
If connected successfully it is shows that result onto the website.
What I'd need it to do is not show up on the html but be there in the file so I can test the file executing in the CLI(Command Line Interface) of PHP.
I am using require_once(); in the index file.
uncomment the echo line. or use php's error_log('Connected Successfully');. this would log that the connection was successful. This would hide output from your html and log the string passed as parameter to your error_log file
One could easily dispense with the echo statement and instead return the connection object upon success. This would entail revising the OP code so that it becomes the contents of a database connect function. This idea I gleaned from binpress.com and include suggestions from the Manual, too:
<?php
/* Assuming that user name,password and database name are
credentials that come from a file outside of the
document root for security. */
function db_connect() {
static $conn;
$servername = "localhost";
if ( !isset( $conn ) ) {
// load and parse file containing credentials:
$config = parse_ini_file('../config.ini');
// Create connection
$conn = new mysqli( $servername, $config['username'],$config['password'],
$config['dbname']);
// Check connection
if ($conn->connect_error) {
die('Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
// Connected successfully
return $conn;
}

How to fix: Error- No database selected

SERVER RESPONSE
Error: INSERT INTO epiz_19848473_Liste1 (Rowcount, Level1) VALUES (0, 'any Value')
No database selected
PHP CODE
UPDATE
<?php
$servername = "sql308.epizy.com";
$username = "epiz_19848473";
$password = "huihuibuh";
$dbname = "Liste1";<--UPDATED
// Create connection
$conn = mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Liste1 <--UPDATED (Rowcount, Level1)
VALUES (0, 'any Value')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
This should work, right?
NEW STATUS
Connection failed: Access denied for user 'epiz_19848473'#'192.168.0.%' to database 'Liste1'
The code is perfectly all right , the problem is with mysql configuration .
Please login to mysql as **root user ** and do the following,
GRANT ALL PRIVILEGES ON . TO 'epiz_19848473'#'192.168.0.%' (use ip of php server)
FLUSH PRIVILIGES;
The above allows the user to connect to mysql table from the ip specified.
you did not defined the database name in the connection
<?php
$servername = "sql308.epizy.com";
$username = "epiz_19848473";
$password = "huihuibuh";
$dbname = "DATABASE_NAME_HERE";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
else you can define define the database name in the connection
$conn = new mysqli($servername, $username, $password, "DATABASE_NAME_HERE");
Just define the dbname,like this:
<?php
$servername = "sql308.epizy.com";
$username = "epiz_19848473";
$password = "huihuibuh";
$dbname = "test"; //You should create this db in mysql
....
You Can Use This:
CREATE TABLE [database_name].[table_name] (
[your_table_things]
);

Global database connection inside functions

Trying to global database connection in all functions in a .php file.
sql.php:
<?php
$servername = "XXXXX";
$username = "XXXXX";
$password = "XXXXX";
$dbname = "XXXXX";
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_set_charset($conn, "utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
save.php
$conn = require_once('../path/to/sql.php');
function save()
{
global $conn;
$sql = "INSERT INTO `content` (title, text, cat)
VALUES ('".$_POST["title"]."', '".$_POST["text"]."', '".$_POST["category"]."')";
if ($conn->query($sql) === TRUE) {
show();
}
$conn->close();
}
well i want to get sql.php with require_once and then make it global then put this in save() function.
error is:
Fatal error: Call to a member function query() on a non-object in
/homepages/3/xxxxxxxx/htdocs/xxxxxxxx/xxxxxxxx/content.php on line 37
actually i don't know this way to make it global is correct or not, so please help me to choose best way to make a global database connection inside the functions.
Try
define('DATABASE_USERNAME', 'root');
define('DATABASE_PASSWORD', 'password');
define('DATABASE_HOST', 'localhost');
define('DATABASE_DBNAME', 'db');
$conn = new mysqli(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_DBNAME);
Named constants are great for static global data.
Also you just need to do
require_once 'path/to/sql.php';
And not
$conn = require_once 'path/to/sql.php';
$conn is already being set in your require_once.

Categories