mysqli migration issue and security advices - php

I tried to migrate from mysql to mysqli but this code doesn't work. I'm new to php and mysql
$link = mysqli_connect("localhost", "user", "password", "db");
/* check connection */
if (mysqli_connect_errno()) { printf("Connect failed: %s\n",
mysqli_connect_error()); exit(); }
if ($result = mysqli_query($link, "SELECT * FROM users WHERE uid='$uid'")) {
if(mysqli_num_rows($result) != 0) {
mysqli_query($link, "UPDATE users SET array='$array' WHERE uid='$uid'");
}
else {mysqli_query($link, "INSERT INTO users (uid,array) VALUES ('$uid','$array')"); }
mysqli_free_result($result); }
/* close connection */
mysqli_close($link);
?>
So my questions are:
what should be changed to make this code work;
what security vulnerabilities does this code have and what changes in the code would you suggest to fix that?
Thanks for spending time to answer my questions.

You need to set error reporting to maximum level and make error messages available. this way you will let PHP to tell you what is going wrong and what needs to be fixed.
however, sometimes our code still doesn't work yet there are no error messages around. it's time to do some debugging
You have to change this code to make every variable to go into query via placeholder only
however, raw mysqli is extremely bad with prepared statements, so, I would recommend not to use it but rather move toward PDO or safeMysql. A latter one will let you to have safe queries with the same amount of code.
if ($db->getOne("SELECT 1 FROM users WHERE uid=?i",$uid))
{
$db->query("UPDATE users SET array=?s WHERE uid=?i",$array,$uid);
} else {
$db->query("INSERT INTO users (uid,array) VALUES (?i,?s)",$uid,$array);
}
By the way, Mysql lets you to make all these three queries in one:
$sql = "INSERT INTO users (uid, array) VALUES (?i,?s)
ON DUPLICATE KEY UPDATE array=values(array)";
$db->query($sql, $uid, $array);

Related

php - MySQL Error 1040 "Too many connections"

I have this error, I have seen on several pages how to fix it, increasing the max connections variable, but I was wondering if there is any way to retry connecting 'n' number of times before throwing that error,
I am using mysqli to create my connection.
I would be very grateful for any help you could give me to get an idea of ​​how to do it if possible
update
con.php
<?php $con = new mysqli("localhost", "root", "", "grmv");
if($conexion->connect_errno) {
die ("Error: " . $con->connect_errno . "---" . $con->connect_error);
}
return $con;
?>
Products.php
<?php
include"con.php";
mysqli_query($con,"SET NAMES 'utf8'");
$result=mysqli_query($con,"select * from bio, carac where idprod=5");
while($data=mysqli_fetch_array($result)){
....
}
$conexion->close();
}
?>
More consistent way is to keep using OOP aproach, also good practice to use bind for any untrusted input, maybe not here specifically but still good practice.
$mysqli = new mysqli(
$connectionData['DB_HOST'],
$connectionData['DB_USER'],
$connectionData['DB_PASSWORD'],
$connectionData['DB_NAME']
);
$mysqli->set_charset('utf8');
$stmt = $mysqli->prepare("select * from bio, carac where idprod=?");
$stmt->bind_param('5');
$stmt->execute();
while ($result = $stmt->fetch()) {
// do stuff
}
$stmt->close();

Transaction is not working - PHP and MySql

I'm beginner to PHP transaction concept. My code is not working. I don't know what is my mistake. Anyone help me to find out my mistake.
My first query is wrong one. It didn't work. Second is successfully executed. If I have checked by IF condition, My control successfully moved to else part. It's fine. But My rollback function not working. Second query date will be present in table.
What is my mistake?
<?php
$link = mysqli_connect("localhost", "root", "", "hrms_db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Transaction start */
mysqli_begin_transaction($link, MYSQLI_TRANS_START_READ_WRITE);
/* disable autocommit */
mysqli_autocommit($link, FALSE);
$result1 = mysqli_query($link, "INSERT INTO EmployeeBackup (Name, OfficialEmail, Department, Manager_ID, MobileNO, Status, Location, full_name) value ('s', 's', '1' , '3', '5', '4', '5' , '78')");
$result2 = mysqli_query($link, "INSERT INTO hrms_general_master (lookup_type, lookup_description) value ('Testing', 'Testing')" );
if($result1 && $result2){
/* commit insert */
mysqli_commit($link);
echo "All queries were executed successfully";
} else{
/* Rollback */
mysqli_rollback($link);
echo "All queries were rolled back";
}
mysqli_close($link);
?>
Then please explain different type of parameter used in mysqli_begin_transaction and use of it. I have little more doubt in mysqli_begin_transaction and mysqli_commit. Please clarify my doubt.
Thank you.
You need the InnoDB access method to use transactions. The people who created MyISAM did not include transactions in their code.
Plenty of tutorials on the net explain DBMS transactions in general, and MySQL transactions in particular. Here is just one.
http://www.tutorialspoint.com/mysql/mysql-transactions.htm

php inserting into a MySQL data field

I am not sure what I am doing wrong, can anybody tell me?
I have one variable - $tally5 - that I want to insert into database jdixon_WC14 table called PREDICTIONS - the field is called TOTAL_POINTS (int 11 with 0 as the default)
Here is the code I am using. I have made sure that the variable $tally5 is being calculated correctly, but the database won't update. I got the following from an online tutorial after trying one that used mysqli, but that left me a scary error I didn't understand at all :)
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
$sql = "INSERT INTO PREDICTIONS ".
"(TOTAL_POINTS) ".
"VALUES('$points', NOW())";
mysql_select_db('jdixon_WC14');
I amended it to suit my variable name, but I am sure I have really botched this up!
help! :)
I think you just need to learn more about PHP and its relation with MYSQL. I will share a simple example of insertion into a mysql database.
<?php
$con=mysqli_connect("localhost","peter","abc123","my_db");
// Check for errors in connection to database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin',35)";
mysqli_query($con, $query);
mysqli_close($con); //Close connection
?>
First, you need to connect to the database with the mysqli_connect function. Then you can do the query and close the connection
Briefly,
For every PHP function you use, look it up here first.
(You will learn that it is better to go with mysqli).
http://www.php.net/manual/en/ <---use the search feature
Try working on the SQL statement first. If you have the INSERT process down, proceed.
You need to use mysql_connect() before using mysql_select_db()
Once you have a connection and have selected a database, now you my run a query
with mysql_query()
When you get more advanced, you'll learn how to integrate error checking and response into the connection, database selection, and query routines. Convert to mysqli or other solutions that are not going to be deprecated soon (it is all in the PHP manual). Good luck!
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
mysql_select_db('jdixon_WC14');
$sql = "INSERT INTO PREDICTIONS (TOTAL_POINTS,DATE) ". //write your date field name instead "DATE"
"VALUES('$points', NOW())";
mysql_query($sql);

Error:NO database is selected

I tried it connection to database connection to database is successful but when i try to match user information with database it gives me a error NO database is selected
i tried it connecting to database using different method but nothing worked
<?php
//CREATING CONNECTION TO DATABASE
$con= new mysqli("localhost", "****", "***", "*****");
$con->select_db("lel_server_user_db_secured");
if(mysqli_connect_errno())
{
echo "Problem With connection to database Please contact administrator regarding this error";
}
/* RETURNS NAME OF DEFAULT DATABASE
if ($result = $con->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
*/
/*
$host="localhost";
$db_user="sky.xpert";
$db_pass="havefun344";
$database="lel_server_user_db_secured";
mysqli_connect($host,$db_user,$db_pass,$database) or die ("Failed to connect");
mysqli_select_db($database) ;
*/
session_start();
//GATHERING DATA FROM USER FORM
$email=$_POST["login"];
$pass=$_POST["pwd"];
//COMMANDING WHERE TO FIND MATCH FOR LGOIN INFORMATION
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$query=mysql_query($veryfy) or die ( mysql_error() );
$match=0;
$match=mysql_num_rows($query);
//IF MATCH FOUND THEN SETTING SESSION AND REDIRECTING IT TO LOGGED PAGE
if($match==1)
{
$_SESSION['loggedin'] = "true";
header ("Location: logged.php"); //REDIRECTING USER TO ITS HOMEPAGE
}
else //IF MATCH NOT FOUND THEN REDIRECTING IT BACK TO LOGIN PAGE
{
$_SESSION['loggedin'] = "false";
header ("Location: index.php");
}
//PERSONAL COMMENTS OR DETIALED COMMENTS
//PROBLEM WITH THIS SCRIPT GIVING OUTPUT ON LOGIN "NO DATABASE SELECTED"
//REFRENCE from http://www.dreamincode.net/forums/topic/52783-basic-login-script-with-php/
?>
You are initializing a connection to your database with mysqli. Then you try to do queries with mysql. Obviously, there is no connection with the database made through that library, and therefore it fails with an error. Change mysql_query to mysqli_query.
General note
Your current code is vulnerable to sql injection attacks, because you do not sanitize the input from the user before putting it in a query. Consider using prepared queries.
The database lel_server_user_db_secured may be not exist.
Content to your mysql:
mysql -hlocalhost -uusername -p
then input your password. After login, type command:
show databases;
check if lel_server_user_db_secured is in the result.
update1*
change the code below:
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$query=mysql_query($veryfy) or die ( mysql_error() );
$match=0;
$match=mysql_num_rows($query);
to:
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$result = mysqli_query($con, $veryfy) or die ( mysqli_connect_errno() );
$match=0;
$match=mysqli_num_rows($result);
var_dump($match);
In the first half of your program you have used mysqli and in the latter half mysql. Either use mysqli or mysql. I would recommend using mysqli in your entire program so that you are not vulnerable to SQL injection
you can simply do it by
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
there is no need to do $con->select_db("lel_server_user_db_secured"); again
and using mysqli isnt mean your code is safe ... your code is still vulnerable to SQL injection Use prepared statement instead or atleast mysqli_real_escape_string
You need to escape all request properly
and its possible that your database isnt exist so check that its exist first
AND you are mixing tow different API
you can not use MySQLi functions with MySQL_* function

Basic MySQL help? - submitting data

I've been getting better at PHP - but I have NO idea what I'm doing when it comes to MySQL.
I have a code
<IMG>
I need to grab the "for", "affi" and "reff" and input them into a database
//Start the DB Call
$mysqli = mysqli_init();
//Log in to the DB
if (!$mysqli) {
die('mysqli_init failed');
}
if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!$mysqli->real_connect('localhost', 'USERNAME', 'PASSWORD', 'DATABASE')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
That's what I'm using to create a connection. It works. I've also got a table created, call it "table", with rows for "for", "affi", and "reff".
So my question is... someone gets directed to http://www.example.com/test.php?for=abcde&affi=12345&reff=foo
Now that I've got a DB connection open - how do I SEND that data to the DB before redirecting them to their destination site? They click - pass across this page - get redirected to destination.
BONUS KARMA - I also need a separate PHP file that I can create that PULLS from that data base. If you could point me at some instructions or show me a simple "how to pull this rows values from this table" I would be greatly appreciative :)
If I understand correctly, you'll want to use $_GET to get the URL parameters.
Then you want to run an insert query on the db with the values you got, which should be something like:
INSERT INTO table VALUES(x, y, z)
Then you need to change the page using a location header.
For the bonus question you just need the code you have now with a select query like:
SELECT * FROM table WHERE 1;
and then fetch the query results.
If this does not answer your questions please provide some clarifications.
Mysqli is the deprecated function and now PDO is recommended to connect to database. You could do following.
<?php
$conn = new PDO('dblib:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $conn->query($sql);
?>
Read more here.

Categories