converting mysql to the new mysqli API - php

I am trying to convert my mysql command to fit the new standard of mysqli and I will post the scripts and then the questions. I already created the table in the database.
config.php:
$dbhost="databasehost";
$dbusername="username";
$dbpassword="password";
$dbname="databasename";
$connect = mysql_connect($dbhost, $dbusername, $dbpassword);
mysql_select_db($dbname,$connect) or die ("Could not connect to database");
?>
insert.php:
include("config.php");
if (isset($_POST[firstname]) && isset($_POST[lastname]) && isset($_POST[age])) {
$sql = "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
mysql_query($sql, $connect);
header("Location: add.htm");
// "1 record added";
}
else {
echo "no record added";
}
if (!mysql_query($sql,$connect))
{
die('Error: ' . mysql_error());
}
mysql_close($connect);
?>
view.php:
<?php
include("config.php");
$sql = mysql_query("SELECT * FROM Persons");
if ($sql) {
while($results = mysql_fetch_array($sql)) {
echo $results['FirstName'] . ', ' . $results['LastName'] . ', ' . $results['Age'] . '<br/>';
}
} else {
die('Error: ' . mysql_error());
}
mysql_close($connect);
?>
First, how do I modify the scripts to use the mysqli instead of mysql?
Second, when using the above script, when I add something from the
form it always add duplicate entry. How do I prevent that?
Third, to prevent sql injection what can I add to the code? I know
for php attach I can use "$firstname =
trim(strip_tags(stripslashes($_POST['firstname'])));" Will that also
cover sql injection since I am sanitizing the input?

kindly read through the official manual for the migration :
https://wikis.oracle.com/display/mysql/Converting+to+MySQLi

Related

MySql Insert into.....(error)

I'm getting an insert error when I'm trying to insert data from a form to my database. the error is as follows :
Error: INSERT INTO users (firstname) VALUES ('a')
This is the code:
if ( isset($_POST['submit']) ) {
$registerfirstname = $_POST['firstname'];
$query = "INSERT INTO users (firstname) VALUES ('$registerfirstname')";
if(mysqli_query($conn, $query)){
echo "New user created";
}else{
echo "Error: " .$query. "<br>" . mysqli_error($conn);
}
}
You are making a little mistake here. You have to pass the variable data through the mysqli_real_escape_string() through first. An example would be ,
$registerfirstname = mysqli_real_escape_string($registerfirstname);
And after that you can use it in sql like that. This way it is more sanitized. I hope this will solve your problem.
Firstly, you should use Mysql Workbenck to prepare sql statements. If, The statements properly work on workbench.Paste into the php script.
On php side, you should use mysql_real_escape_string() function before set your variable.
Like;
$registerfirstname = mysql_real_escape_string($_POST['firstname']);
Try this:
// Create connection
$connection = new mysqli('localhost', 'username', 'password', 'dbname');
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$firstname = "John";
$firstname = mysqli_real_escape_string($firstname);
$sql = "INSERT INTO users (firstname) VALUES ('$firstname')";
if ($connection->query($sql) === TRUE) {
echo "New user created";
} else {
echo "Error: " . $sql . "<br>" . $connection->error;
}
// Close connection
$connection->close();
It should work, but if it doesn't just give us what errors are shown.

SQL in PHP failure

If the value of the result is 0 it has to go to 'cid_check_firstdep.php' otherways (if its 1) it has to go to 'cid_check_depwid.php'.
It has to work, but i don't know why it doesn't. I've tried what i could that i think would be possible to fix it, but nono.
Code:
<?php
$con = mysql_connect("localhost","root","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
header('Location: /ucp/error.php');
}
$sql = "SELECT validated FROM users WHERE username='".($_SESSION['username'])."'";
mysql_select_db("bluecard");
mysql_query($sql,$con);
if ($sql<'1')
{
mysql_close($con);
header('Location: /ucp/cid_check_firstdep.php');
}
else
{
mysql_close($con);
header('Location: /ucp/cid_check_depwid.php');
}
?>
or do i have to use :
if ($sql=='0')
?
|||
#John Conde
<?php
if(! get_magic_quotes_gpc() )
{
$withdraw = addslashes ($_POST['withdraw']);
}
else
{
$withdraw = $_POST['withdraw'];
}
$con = mysql_connect("localhost","root","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
header('Location: /ucp/error.php');
}
$__sql = "SELECT cardvalue FROM users WHERE username='".($_SESSION['username'])."'";
mysql_select_db("bluecard");
mysql_query($__sql,$con);
if ($__sql<'5000000')
{
header('Location: /ucp/includes/withdraw_fail.php');
mysql_close($con);
}
else
{
$_sql = "UPDATE users SET Bank=Bank + '$deposit' WHERE Username='".($_SESSION['username'])."'";
mysql_select_db("server");
mysql_query($_sql,$con);
$sql = "UPDATE users SET cardvalue=cardvalue +- '$deposit', thismonth_withdraw=thismonth_withdraw + '$deposit', lastwithdraw = Now() WHERE username='".($_SESSION['username'])."'";
mysql_select_db("bluecard");
mysql_query($sql,$con);
mysql_close($con);
header('Location: /ucp/includes/withdraw_done.php');
}
?>
You're checking the wrong variable for your SQL result. You're using the variable containing your query instead of the variable you never assigned to capture the result of mysql_query(). You also want to use mysql_num_rows() to see how many results were returned.:
$result = mysql_query($sql,$con);
if ($result && mysql_num_rows($result) == 1) {
FYI, you shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Hi Morgan I change your code according to my knowledge. I think this will help you to work done.
If you found any match to the username "count($return_data)" will get 1.
Thanks.
<?php
$con = mysql_connect("localhost","root","password");
$select_db = mysql_select_db("bluecard");
if (!$con)
{
die('Could not connect: ' . mysql_error());
header('Location: /ucp/error.php');
}
$sql = "SELECT validated FROM users WHERE username='".($_SESSION['username'])."'";
$query = mysql_query($sql,$con);
$return_data = array();
while($rows = mysql_fetch_array($query)){
$return_data[]=$rows;
}
if (count($return_data)<=1)
{
mysql_close($con);
header('Location: /ucp/cid_check_firstdep.php');
}
else
{
mysql_close($con);
header('Location: /ucp/cid_check_depwid.php');
}
?>

No database selected when trying to setup query in php

Ok i get the following error "No database selected" when trying to run a query in php. the connect file in in the connect.inc.php file and that returns no error. i an learning php so any help i thank you. Also to note the query works in phpmyadmin panel with no errors
<?php
require 'connect.inc.php';
$sql = "SELECT `name`, `address`, `city` FROM `customers` ORDER BY `id`";
if ($sql_run = mysql_query($sql)) {
echo 'Success.';
} else {
echo mysql_error();
}
?>
The mysql library is deprecated, use mysqli or PDO.
With mysqli, you can also select the database directly when you're creating the connection (and I recommend doing that when possible, if you're only working with one database) :
$db = mysqli_connect("<host>","<username>","<password>","<database>");
Replace <database> with the DB you want to use.
Either use in your connect.inc.php the mysql_select_db function just after mysql_connect:
mysql_select_db('your_database_name');
or add the database name in every query:
$sql = "SELECT `name`, `address`, `city` FROM `your_database_name`.`customers` ORDER BY `id`";
Note that the mysql library is deprecated and you should use mysqli or PDO. If you're learning, run away from any "tutorial" that still uses these deprecated functions.
hope you write write script to connect DB in this way or you can try this....
$connection = mysql_connect("$dbhost","$dbusername","$dbpass");
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
else
{
echo "Connected";
$dbcheck = mysql_select_db("$dbname");
if (!$dbcheck) {
echo mysql_error();
}else{
echo "<p>Successfully connected to the database '" . $database . "'</p>\n";
}
}
This is a basic example i have kind of filled in with your code. You will need to fill in the vars with FILL THIS as values.
<?php
$host = "FILL THIS";
$db = "FILL THIS";
$user = "FILL THIS";
$pass = "FILL THIS";
$link = mysql_connect($host,$user ,$pass);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db($db, $link);
if (!$db_selected) {
die ('Can\'t use database : ' . mysql_error());
}
require 'connect.inc.php';
$sql = "SELECT `name`, `address`, `city` FROM `customers` ORDER BY `id`";
if ($sql_run = mysql_query($sql,$link)) {
echo 'Success.';
} else {
echo mysql_error();
}
mysql_close($link);
?>

Display error if the email address entered in form already exists

How do I use "emailaddress" as the only duplicate entry that provides a error?
A lot of the answers I've found use mysql_query but I want to use mysqli.
<?php
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO entry (firstname, lastname, emailaddress, favoritesong) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[emailaddress]','$_POST[favoritesong]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
WARNING! the posted code and this answer (as i am only addressing the question now) contain big SQL injection leaks. Please read up on SQL injection and use escaping or prepared statements.
<?php
$con = mysqli_connect("localhost", "", "", "");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$existsQuery = "select count(*) as count from entry where emailaddress like '".$_POST[emailaddress]."'";
$existsResult = mysqli_query($con, $existsQuery);
if($existsResult->fetch_object()->count > 0)
{
echo "email already exist";
}
else
{
$sql = "INSERT INTO entry (firstname, lastname, emailaddress, favoritesong) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[emailaddress]','$_POST[favoritesong]')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
mysqli_close($con);
?>
simply make emailaddress unique in your table.

Do Not Duplicate VALUE if already exist on MySQL

I've been trying to accomplish this, but as other issues I just can't figured it out. I've been reading around for posibles solutions but non of them goes along with my code, or if they do I can't figure out how or where to use them.
I have a DB where a user sends records. The database consist in few tables containing the Following "Name, Lastname, Phone". If any of this values is duplicate, I would like my code to identify and Ignore the submission of the Form if ALL this VALUES already exist on the DB.
Here is my code:
<?php
$con = mysql_connect("HOST","USER","PASS");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testdb", $con);
$sql="INSERT INTO people (Name, LastName, Phone)
VALUES
('$_POST[Name]','$_POST[LastName]','$_POST[Phone]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Record Added";
mysql_close($con);
?>
The mysql_* function are all deprecated now, and should NEVER be used. change your code to do something like the following:
//Set up a PDO connection to MySQL
$host = 'host_name';
$dbname = 'database_name';
$user = 'user_name';
$pass = 'user_pass';
try
{
$DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
//Determine whether the appropriate values have been passed.
if(isset($_POST['Name']))
{
$name = $_POST['Name'];
}
else
{
echo "You must provide a name!";
exit; //This may not be what you want to do here, it's an example action
}
if(isset($_POST['LastName']))
{
$name = $_POST['LastName'];
}
else
{
echo "You must provide a last name!";
exit; //This may not be what you want to do here, it's an example action
}
if(isset($_POST['Phone']))
{
$name = $_POST['Phone'];
}
else
{
echo "You must provide a phone number!";
exit; //This may not be what you want to do here, it's an example action
}
//Set up the query using anonymous values
$sql="INSERT INTO people (Name, LastName, Phone) VALUES ('?','?','?')";
$sth = $DB->prepare($sql);
try
{
//Attempt to execute the insert statement
$sth->execute(array($_POST[Name], $_POST[LastName], $_POST[Phone]));
echo "Record Added";
}
catch(PDOException $e)
{
//If the insert failed, then you can handle the error, and determine
//what further steps need to be taken.
echo "Record Not Added";
}
Here's another question with a similar setting, that may also be useful to you:
https://stackoverflow.com/a/10414922/1507210
search in the table before insert
<?php
$con = mysql_connect("HOST","USER","PASS");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testdb", $con);
$name = mysql_real_escape_string($_POST[Name]);
$LastName= mysql_real_escape_string($_POST[LastName]);
$Phone= mysql_real_escape_string($_POST[Phone]);
$search_res=mysql_query("SELECT * from people where Name='$Name' OR LastName='$LastName' OR Phone='$Phone'");
if(mysql_num_rows($search_res) < 1){
$sql="INSERT INTO people (Name, LastName, Phone)
VALUES
('$Name','$LastName','$Phone')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Record Added";
}else{
echo "User Already exits";
}
mysql_close($con);
?>
Try this easy solution
$result = mysql_query("SELECT * FROM TABLE WHERE Column = 'value' ");
if( mysql_num_rows($result) < 1) {
mysql_query("INSERT INTO table (column) VALUES ('value') ");
}

Categories