Converting mysql_real_escape to it's MySQLi equivalent [duplicate] - php

This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 7 years ago.
I have this code:
<?php
#include_once('set.php');
#include_once('steamauth/steamauth.php');
if(!isset($_SESSION["steamid"])) {
Header("Location: index.php");
exit;
}
$link = $_POST["link"];
$link = mysql_real_escape_string($link);
$steam = $_SESSION["steamid"];
mysql_query("UPDATE users SET `tlink`='$link' WHERE `steamid`='$steam'");
Header("Location: settings.php");
exit;
?>
And I need to convert it to MySQLi because it's completely useless in's current state. Changing the "mysql_" to "mysqli_" doesn't work at all.

I think this is what you're looking for.
<?php
require_once('set.php');
require_once('steamauth/steamauth.php');
if(!isset($_SESSION["steamid"])) {
header("Location: index.php");
exit();
}
$steam = $_SESSION["steamid"];
// Open a new connection to the MySQL server
$connection = new mysqli($host, $username, $password, $databaseName);
// Check connection
if($connection->connect_errno){
// error
die('Connect Error: ' . $connection->connect_error);
}
// Escapes special characters in a string for use in an SQL statement
$link = $connection->real_escape_string($_POST["link"]);
// Execute query
$connection->query("UPDATE users SET tlink='{$link}' WHERE steamid='{$steam}'");
// Close connection
$connection->close();
header("Location: settings.php");
exit();
?>

Related

PHP SQL Server Connection working or not working [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 4 years ago.
$serverName = 'servername';
$uid = 'username';
$pwd = 'password';
$conn = new mysqli($serverName, $uid, $pwd );
if (!$conn) {
echo "Connection failed: " ;
}
else
{
echo "Connected successfully";
}
This is my code. It gets connected to the database. I just want to confirm the code is right, because when i try doing this
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
it throws me connection failed error.
So, is my code connected to the server or not? because when i run a query it does not show me anything.
Code for the query:
$sql = "SELECT max([line_nbr]) FROM [dbo].[so_audit]";
$res = $conn->query($sql);
var_dump($res);
please advise
you are not trying to connect to sql server u should use sqlsrv_connect instead of mysqli
so u need to specify the server name and an array containin connection info for that your code should look like this :
$srv ="servername"
$info=array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $srv, $info);
if (!$conn) {
echo "Connection failed: " ;
}
else
{
echo "Connected successfully";
}

PHP coding got an error [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
<?php
$conn=mysql_connect(`localhost'," root","") or die("Could not connect");
mysql_select_db("bng_nov",$conn) or die("could not connect database");
?>
Parse error: syntax error, unexpected end of file, expecting '`' in C:\xampp\htdocs\display\db.php on line 4
Error in this line replace (`) with (') single quote. also remove space before root
$conn=mysql_connect('localhost',"root","") or die("Could not connect");
and best solution is use double quotes like this
$conn=mysql_connect("localhost","root","") or die("Could not connect");
also i mention that don't use mysql_*. you should used mysqli_*
i have add some DB connectivity codes. used this code
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
error in the below line
$conn=mysql_connect(`localhost'," root","")
please try like below
<?php
if (!$link = mysql_connect('localhost', 'root', '')) {
echo 'Could not connect to mysql';
exit;
}
if (!mysql_select_db('bng_nov', $link)) {
echo 'Could not select database';
exit;
}
?>

Data is not inserting into table?

GYZ i dont know why data is not inserting in my data base #Mysql
. infact im using mysqli_connect and mysql_connect both ,I'm still facing same prob ..this is my code:
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$db='school';
#mysqli_connect($servername, $username, $password);
#mysqli_select_db($db); //or die ('not Connect to db ');
if(isset($_GET['submit'])) {
$sid= $_GET['sid'];
$sname= $_GET['sname'];
$fname= $_GET['fname'];
$order= #mysqli_query("insert into school (sid,sname,fname) values ('$sid','$sname','$fname');");
if ($order) {
echo '<br>Input data is successful';
} else {
echo '<br>Input data is not valid';
}
} ?>
I revisited the question and posted the following, seeing that nobody posted one.
You didn't pass the db connection to mysqli_select_db() nor for mysqli_query() and need to assign a variable to the connection first.
Both of those require it in mysqli_ and you may have been accustomed to mysql_ in the past. MySQLi_ is different than MySQL_ when it comes to certain functions that needs a connection.
Sidenote: The # symbol is an error suppressor. Remove it during testing/development.
Another sidenote: Both your database and table bear the same name of school. Make sure that this is correct.
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$db='school';
$connect = mysqli_connect($servername, $username, $password, $db);
if($connect){
echo "Connected";
}
else {
echo "Error: " . mysqli_error($connect);
}
// This isn't needed. You can pass all 4 parameters in one shot.
// $database = mysqli_select_db($connect, $db); //or die ('not Connect to db ');
if(isset($_GET['submit'])) {
$sid= $_GET['sid'];
$sname= $_GET['sname'];
$fname= $_GET['fname'];
$order= mysqli_query($connect, "INSERT INTO school (sid,sname,fname) VALUES ('$sid','$sname','$fname');");
if ($order) {
echo '<br>Input data is successful.';
} else {
// Uncomment the one below once everything is ok.
// echo '<br>Input data is not valid.';
// Comment this below once there are no errors.
echo "There was an error: " . mysqli_error($connect);
}
}
References:
http://php.net/manual/en/function.mysqli-connect.php
http://php.net/manual/en/mysqli.select-db.php
http://php.net/manual/en/mysqli.query.php
Check for errors also via PHP and the query:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
And make sure you're running this off a webserver, or if local that PHP/MySQL are installed, running properly and using http://localhost as opposed to file:///.
Your code is also open to an SQL injection, use a prepared statement.
References:
https://en.wikipedia.org/wiki/SQL_injection
https://en.wikipedia.org/wiki/Prepared_statement
Footnotes:
You seem to want to use this in a table. <form> cannot be child of <table> if you are using those tags outside of the form which wasn't posted in your question; there are stray <td></td> tags.

Login Script in php to my MYSQL shows Deprecated warning [duplicate]

This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 8 years ago.
I'm writing a simple program in php that requires users to login. I have a working code but whenever a wrong username or password is entered, I got an exception that says the following:
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\Directory\login.php on line 67
The script I have is working well, but I just need to get rid of this warning message.
Below is my php code.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// Connect to the database
$con = mysql_connect('localhost', 'root', '');
// Make sure we connected succesfully
if (!$con) {
die('Connection Failed' . mysql_error());
}
// Select the database to use
mysql_select_db("Garden", $con);
$q = mysql_query("select * from register where username='" . $username . "' and password='" . $password . "' ") or die(mysql_error());
$res = mysql_fetch_row($q);
if ($res) {
header('location:home.php');
} else {
echo 'Error. The Username or Password that you entered is invalid.';
}
?>
I dont know if im using something. This is my first time of using php. Please I need your help. Thank you.
Here's the same code using MySQLi:
<?php
$mysqli = new mysqli('localhost', 'user', 'password', 'db_name');
if(mysqli_connect_errno()){
printf("DB Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Add the UTF8 Support
$mysqli->query("SET NAMES 'utf8'");
$mysqli->query("SET CHARACTER SET utf8");
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$username = $mysqli->real_escape_string($username);
$password = $mysqli->real_escape_string($password);
$query = "SELECT * FROM `register` WHERE username='" . $username . "' and password='" . $password . "' LIMIT 1";
$result = $mysqli->query($query);
if(!empty($result)){
if($result->num_rows == 1) {
header("Location: home.php");
} else {
echo "Error. The Username or Password that you entered is invalid.";
}
}
mysqli_close($mysqli);
$mysqli = null;
?>
You shouldn't be avoiding the PHP Errors. You should always fix the code accordingly.
You can use PDO or MySQLi.
Rewrite your code (small effort) using mysqli even if it's working properly and check if the message still appears.

Check whether a mysql_connect() failed or not?

Hey i'm trying to find out whether my sql query failed or not. I want it so if it does fail redirect to form page using the code below:
$checkconnection = mysql_connect('localhost', $dbuser, $dbpass)
or die();
if(!$checkconnection)
{
$_SESSION['errormsg'] = "<div style='padding-left: 50px;color:#FF0000'>Cannot connect to specfied database!</div>";
header("Location: install.php");
}else{
echo('Connection Successful!');
}
using that all it says is this:
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'nzcraftn_admin'#'localhost' (using password: YES) in /home/nzcraftn/public_html/phishnet/install/install_submit.php on line 17
Try this one
$checkconnection = #mysql_connect('localhost', $dbuser, $dbpass)
it will hide default error and trigger your own
The return value of mysql_connect being false only indicates failure. If it returns FALSE, the or die() expression will exit the php script. That's the reason why you don't sea any of it's output.
Remove the or die() command, and display the actual error in your if( !$checkconnection ) clause. The reported error can be retrieved using mysql_error().
It's only displaying the warning because your or die() isn't outputting anything (empty parameter list). Try this instead:
<?php
//Start the session
session_start();
//Do the conntection
$checkconnection = #mysql_connect('localhost', $dbuser, $dbpass);
//Check if it's valid
if(!$checkconnection) {
//Add it up to the session, and redirect
$_SESSION['errormsg'] = "<div style='padding-left: 50px;color:#FF0000'>Cannot connect to specfied database!</div>";
session_write_close();
header("Location: install.php");
exit();
} else{
//Yay
echo('Connection Successful!');
}
?>
The answer by genesis just supresses the warning, but still might work
If you want it 'clean' you can try/catch the error:
(directly from the comments on php.net/mysql_connect:
// Assign variables
global $db_connection, $db_server, $db_database, $db_username, $db_password;
$db_server = $server;
$db_database = $database;
$db_username = $username;
$db_password = $password;
// Attempt connection
try
{
// Create connection to MYSQL database
// Fourth true parameter will allow for multiple connections to be made
$db_connection = mysql_connect ($server, $username, $password, true);
mysql_select_db ($database);
if (!$db_connection)
{
throw new Exception('MySQL Connection Database Error: ' . mysql_error());
}
else
{
$CONNECTED = true;
}
}
catch (Exception $e)
{
echo $e->getMessage();
}

Categories