MySQL to MySQLi conversion php form - php

I kinda ran into a problem with my form which is connected with the DB through the outdated MySQL. I'm trying to convert this to MySQLi following online sources and my own knowledge but it doesn't seem to do the trick. I have checked stackoverflow (How to solve Mysql to mysql as I have some problems) which does cover the convertion for some points but as I have some extra functions I dont quite know how to go. Also, is the striplashes function still necessary when using MySQLi? Your help and time is much appreciated, the script goes as follow:
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = false;
if(empty($_POST['formName']))
{
$errorMessage = true;
}
if(empty($_POST['formEmail']))
{
$errorMessage = true; }
if(empty($_POST['formAddress']))
{
$errorMessage = true; }
if(empty($_POST['formPrice']))
{
$errorMessage = true; }
$varName = $_POST['formName'];
$varEmail = $_POST['formEmail'];
$varAddress = $_POST['formAddress'];
$varPrice = $_POST['formPrice'];
$varComments = $_POST['formComments'];
if($errorMessage == false)
{
$db = mysql_connect("","","");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("" ,$db);
$sql = "INSERT INTO formdata (name, email, address, price, comments) VALUES (".
PrepSQL($varName) . ", " .
PrepSQL($varEmail) . ", " .
PrepSQL($varAddress) . ", " .
PrepSQL($varPrice) . ", " .
PrepSQL($varComments) . ")";
mysql_query($sql);
header("Location: thankyou.php");
exit();
}
}
//sql injection protection..
function PrepSQL($value)
{
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
I had the connecting part working but It didnt write to the DB so I think the query part went wrong.

Just basic changes :
$link = mysqli_connect('localhost','root','pass','myDB');
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
$sql= "INSERT INTO keypairs (name, email, address, price, comments) VALUES ('$varName','$varEmail','$varAddress','$varPrice','$varComments')";
if (!mysqli_query($link,$sql)) {
//error ...
}

Related

Inserting data into two mysql tables using mysql and php

I have two tables named 'Students_tbl' and 'admission'. I want to insert admission number in both tables at the same time such that in the 'students_tbl', it is a foreign key while in the 'admission' table, it is a primary key. The 'students_tbl' has a primary key of "std_index"
I am using one html form.
The codes I have written are outputting an error. Thanks for your replies in advance
Here are the codes
<?php
$manzu =mysqli_connect("localhost","root","MANZu1992", "cdms");
// Check connection
if (!$manzu) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
echo "Please Check your connection. We were unable to connect you to the desired site.";
}
if (isset($_POST['submit'])) {
$identification = mysqli_real_escape_string($manzu, $_POST['iddd']);
$National_Number = mysqli_real_escape_string($manzu, $_POST['national_Numberr];
$sql = "INSERT INTO students_tbl (std_index,std_national_number)
VALUES ('$identification','$National_Number')";
$sql = "INSERT INTO admission (Admission_Number)VALUES($National_Number)";
if (!mysqli_query($manzu,$sql)) {
die('Error: ' . mysqli_error($manzu));
}ELSE {
die ('Thank you for registering');
}
}
?>
You are missing a closing bracket and quote
You're not executing the first query before overwriting $sql
<?php
$manzu =mysqli_connect("localhost","root","MANZu1992", "cdms");
if (!$manzu) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
echo "Please Check your connection. We were unable to connect you to the desired site.";
}
if (isset($_POST['submit'])) {
$identification = mysqli_real_escape_string($manzu, $_POST['iddd']);
$National_Number = mysqli_real_escape_string($manzu, $_POST['national_Numberr']);
$sql = "INSERT INTO students_tbl (std_index,std_national_number) VALUES ('$identification','$National_Number')";
mysqli_query($manzu,$sql);
$sql = "INSERT INTO admission (Admission_Number)VALUES($National_Number)";
if (!mysqli_query($manzu,$sql)) {
die('Error: ' . mysqli_error($manzu));
}else {
die ('Thank you for registering');
}
}
?>

Why my mysql transaction is not working properly?

I've been reading and gathering information for 2 days already and I give up. I have no clue why my piece of simple code is not succeeding.
I want to insert data from one form into two tables and YES I know there are exactly same problems described here and there, but as I said I'm familiar with them and also need to ask more questions.
The problem is in my query somewhere, at least this is what I believe it is.
Here it goes:
unset($err);
//Variables
$host = 'my.server.com';
$user = '123';
$pass = 'password';
$dbname = '123';
$err = array();
$error_form = false;
$img = "sth/sth.jpg";
//Connecting to the database using mysqli application programming interface
$con = mysqli_connect($host, $user, $pass, $dbname);
if (!validate()) {
if (!$con) {
echo "Connection failed : <br />" . $new_con->connect_errno . "<br />" . $new_con->connect_error;
exit;
} else {
echo "Connected! <br />";
}
var_dump($name);
echo "<br />";
var_dump($email);
echo "<br />";
var_dump($img);
echo "<br />";
$query= "START TRANSACTION;
INSERT INTO `123`.`table1` (`name1`,`name2`)
VALUES ('". $name . "','". $email ."');
INSERT INTO `123`.`table2` (`table1_id`,`name3`,`name4`)
VALUES (LAST_INSERT_ID(),'". $story . "','". $img ."');
COMMIT;";
var_dump(mysqli_query($con,$query));
echo "<br />";
$_POST["name"] = "";
$_POST["email"] = "";
$_POST["story"] = "";
}
//Form validation
function validate() {
global $name, $email, $story, $err, $error_form;
if($_SERVER['REQUEST_METHOD']=="POST") {
if(isset($_POST["name"]) && !empty($_POST["name"])) {
$name = htmlspecialchars($_POST["name"]);
} else {
$err[0] = "Name is missing.";
$error_form = true;
}
if(isset($_POST["email"]) && !empty($_POST["email"])) {
if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$email = htmlspecialchars($_POST["email"]);
} else {
$err[1] = "Email was verified as incorrect.";
$error_form = true;
}
} else {
$err[1] = "Email is missing.";
$error_form = true;
}
if(isset($_POST["story"]) && !empty($_POST["story"])) {
$story = htmlspecialchars($_POST["story"]);
} else {
$err[2] = "Your story does not contain any characters, it can't be submited.";
$error_form = true;
}
}
return $error_form;
}
Everything what confuses me happens here:
$query= "START TRANSACTION;
INSERT INTO `123`.`table1` (`name1`,`name2`)
VALUES ('". $name . "','". $email ."');
INSERT INTO `123`.`table2` (`table1_id`,`name3`,`name4`)
VALUES (LAST_INSERT_ID(),'". $story . "','". $img ."');
COMMIT;";
var_dump(mysqli_query($con,$query));
I've tried to SELECT the id FROM the table1 table and SET it as a #value instead of LAST_INSERT_ID(). I've tried to run two queries...many different solutions.
I found out when I dump mysqli_query($con,$query) it gives false every time unless I don't use transaction, so just simple queries, but I need them.
Last thing is should I use PDO instead of mysqli? Why?
and
Why to use mysqli object oriented style instead of procedural one?
Every help is appreciated. I would like more to understand than just to achieve the effect here.
Be aware this is my first post here, but not the first visit.
You can only do one query at a time with mysqli_query Look at mysqli_multi_query()
http://www.w3schools.com/php/func_mysqli_multi_query.asp
$query= "START TRANSACTION;
INSERT INTO `123`.`table1` (`name1`,`name2`)
VALUES ('". $name . "','". $email ."');
INSERT INTO `123`.`table2` (`table1_id`,`name3`,`name4`)
VALUES (LAST_INSERT_ID(),'". $story . "','". $img ."');
COMMIT;";
var_dump(mysqli_multi_query($con,$query));

Can't record fields into database (php, SQL)

I'm trying to take a form that a user inputs from an HTML site and send the information to a SQL database. I am able to print out the variables after submission, so I know at the very least the variables are set properly. So I have to assume my code to send the content to the database is at fault here.
Here's the code:
//Taking variables from HTML input
if (isset($_POST['group'])) {
$group = $_POST['group'];
} else {
echo $error; return;
}
if (isset($_POST['game'])) {
$game = $_POST['game'];
} else {
echo $error; return;
}
if (isset($_POST['platform'])) {
$platform = $_POST['platform'];
} else {
echo $error; return;
}
if (isset($_POST['player'])) {
$player = $_POST['player'];
} else {
echo $error; return;
}
if (isset($_POST['play'])) {
$play = $_POST['play'];
} else {
echo $error; return;
}
if (isset($_POST['timezone'])) {
$timezone = $_POST['timezone'];
} else {
echo $error; return;
}
$error = 0;
//Retrieving Databse
try {
//userID and password is defined, just hiding it here
$dbh = new PDO("mysql:host=localhost;dbname=userID", "userID", "password");
} catch (Exception $ex) {
die("<p>($e->getMessage())</p></body></html>)");
}
//Inputting content into MySQL
$command = "INSERT INTO teams ( group, game, platform, player, play, timezone )
VALUES ( '$group','$game','$platform','$player','$play','$timezone')";
$stmt = $dbh -> prepare($command);
if ( ! $stmt->execute() ) {
$error = "<b>ERROR:</b> Could not record fields"; echo $error; return;
}
I'm not really sure where I've gone wrong, could be possible it's the tiniest thing or just something I've overlooked.
Thanks in advance for any help, guys!
This is how I did it for my Assignment:
Connecting to MySQL (notice that I dont have any mysql:host=):
$mysqli = new mysqli("localhost", "username", "pass", "database_name");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
Then in your code, when initializing variabels from POST, escape the strings. This will give you some protection against SQL-Injections:
$Name = $mysqli->real_escape_string($_POST["txtName"]);
$Street = $mysqli->real_escape_string($_POST["txtStreet"]);
$City = $mysqli->real_escape_string($_POST["txtCity"]);
Now, prepare a SQL code to insert your params:
$input = $mysqli->query("INSERT INTO customer (MembershipID, Name, Street, City, PostCode, Email, Password, DateJoin, Salt)
VALUES ('". $MembershipID."','".$Name."','".$Street."','". $City."','". $PostCode."','". $Email."','". $Password."','". $DateJoined."','". $Salt."')");
I hope it helps, Good Luck.

inspect data (url variable) before inserting to mysql

My php script is posting bad urls that ajax send to it. When I try to filter the url and cancel the insert into mysql, it doesn't work. What I want to do is verify the $link variable if it a link. If not, don't post data to mysql. Can i know what I did wrong and how to fix it? Thank you :)
Here is my code
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$link = $_POST['new'];
$name = $_POST['name'];
$size = $_POST['size'];
$cat = $_POST['cat'];
// PHP 5.3.5-1ubuntu7.2
$link = mysql_real_escape_string($link);
$name = mysql_real_escape_string($name);
$size = mysql_real_escape_string($size);
$cat = mysql_real_escape_string($cat);
if (filter_var($link, FILTER_VALIDATE_URL)) {} else {
echo "URL is NOT valid";
mysql_close($con);
exit();
}
$check = mysql_query("SELECT link FROM links WHERE link = '{$link}';");
if (mysql_num_rows($check) == 0) {
// insert
$sql="INSERT INTO links (link, name, size, category) VALUES ('$link','$name','$size','$cat')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added. Redirecting!";
mysql_close($con);
}
try this one:
if(filter_var($link, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) === false){
echo "URL is NOT valid";
mysql_close($con);
exit();
}
Your are right xxxhxtxtp://example.com will pass as valid url.
Try it with preg_match instead.
if (!preg_match("#^http(s)?://[a-z0-9-_.]+\.[a-z]{2,4}#i", $link)) {
echo "URL is NOT valid";
mysql_close($con);
exit();
}
With this regex you need to have http(s) scheme. So you can search for another regex if that don't work for you.
Is this what you're trying to do? Perhaps you need a regex solution.
if (filter_var($link, FILTER_VALIDATE_URL)) {
$check = mysql_query("SELECT link FROM links WHERE link = '{$link}';");
if (mysql_num_rows($check) == 0) {
// insert
$sql="INSERT INTO links (link, name, size, category) VALUES ('$link','$name','$size','$cat')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added. Redirecting!";
mysql_close($con);
}
} else {
echo "URL is NOT valid";
mysql_close($con);
exit();
}

Cannot execute sql INSERT query (mysql_query) in php script. PHP/MySQL -- Time Sensitive

UPDATE: NOW RESOLVED - Thanks everyone!
Fix: I had a column named "referred_by" and in my code it's called "referred_by_id" - so it was trying to INSERT to a column that didn't exist -- once I fixed this, it decided to work!
I have limited time left to work on this project. The clock is ticking.
I'm trying to INSERT $php_variables into a TABLE called "clients".
I've been trying for hours to get this script to work, and I got it to work once, but then I realized I forgot a field, so I had to add another column to the TABLE and when I updated the script it stopped working. I reverted by but now it's still not working and I'm just frustrating myself too much.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if (!isset($_COOKIE["user"]))
{
header ("Location: ./login.php");
}
else
{
include ("./source.php");
echo $doctype;
}
$birthday = $birth_year . "-" . $birth_month . "-" . $birth_day;
$join_date = date("Y-m-d");
$error_type = 0;
$link = mysql_connect("SERVER", "USERNAME", "PASSWORD");
if (!$link)
{
$error = "Cannot connect to MySQL.";
$error_type = 1;
}
$select_db = mysql_select_db("DATABASE", $link);
if (!$select_db)
{
$error = "Cannot connect to Database.";
$error_type = 2;
}
if ($referred_by != "")
{
$result = mysql_query("
SELECT id FROM clients WHERE referral_code = $referred_by
");
if (!$result)
{
$error = "Cannot find referral.";
$error_type = 3;
}
while ($row = mysql_fetch_array($result))
{
$referred_by_id = $row['id'];
}
}
else
{
$referred_by_id = 0;
}
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$birth_month = mysql_real_escape_string($_POST['birth_month']);
$birth_day = mysql_real_escape_string($_POST['birth_day']);
$birth_year = mysql_real_escape_string($_POST['birth_year']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$city = mysql_real_escape_string($_POST['city']);
$state = mysql_real_escape_string($_POST['state']);
$zip_code = mysql_real_escape_string($_POST['zip_code']);
$phone_home = mysql_real_escape_string($_POST['phone_home']);
$phone_cell = mysql_real_escape_string($_POST['phone_cell']);
$referral_code = mysql_real_escape_string($_POST['referral_code']);
$referred_by = mysql_real_escape_string($_POST['referred_by']);
$organization = mysql_real_escape_string($_POST['organization']);
$gov_type = mysql_real_escape_string($_POST['gov_type']);
$gov_code = mysql_real_escape_string($_POST['gov_code']);
$test_query = mysql_query
("
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."')
");
if (!$test_query)
{
die(mysql_error($link));
}
if ($error_type > 0)
{
$title_name = "Error";
}
if ($error_type == 0)
{
$title_name = "Success";
}
?>
<html>
<head>
<title><?php echo $title . " - " . $title_name; ?></title>
<?php echo $meta; ?>
<?php echo $style; ?>
</head>
<body>
<?php echo $logo; ?>
<?php echo $sublogo; ?>
<?php echo $nav; ?>
<div id="content">
<div id="main">
<span class="event_title"><?php echo $title_name; ?></span><br><br>
<?php
if ($error_type == 0)
{
echo "Client was added to the database successfully.";
}
else
{
echo $error;
}
?>
</div>
<?php echo $copyright ?>
</div>
</body>
</html>
Definitely not working as is. Looks you have a 500 error, since you have an else with a missing if:
else
{
$referred_by_id = 0;
}
Otherwise, you'll need to post your DB schema.
Also, note that you're really taking the long way around with this code, which makes it difficult to read & maintain. You're also missing any sort of checks for SQL injection... you really need to pass things through mysql_real_escape_string (and really, you should use mysqli, since the mysql interface was basically deprecated years ago).
$keys = array('first_name',
'last_name',
'birthday',
'join_date',
'email',
'address',
'city',
'state',
'zip_code',
'phone_home',
'phone_cell',
'referral_code',
'referred_by_id',
'organization',
'gov_type',
'gov_code');
$_REQUEST['birthdate'] = $_REQUEST['birth_year'].'-'.$_REQUEST['birth_month'].'-'.$_REQUEST['birth_day'];
$_REQUEST['join_date'] = date('Y-m-d',time());
$params = array();
foreach ($keys as $key)
{
$params[] = mysql_real_escape_string($request[$key]);
}
$sql = 'INSERT INTO clients ('.implode(',', $keys).') ';
$sql .= ' VALUES (\''.implode('\',\'', $params).'\') ';
You've an error on line 81:
else
{
$referred_by_id = 0;
}
I don't see an IF construct before that, make the appropriate correction and run the script again.
Without looking at the table structure to make sure all the fields are there, I'm going to assume it's something with the data.
Any quotes in the data will lead to problems (including SQL injection security holes). You should wrap each $_POST[] with mysql_real_escape_string(), such as:
$first_name = mysql_real_escape_string($_POST['first_name']);
EDIT: Further debugging...
As someone suggested (sorry, can't find the comment), try:
$sql = "
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."'
)";
// Debug:
print "<pre>". $sql ."</pre>";
mysql_query($sql);
The SQL statement should be printed out when submitting the form. Take that SQL statement and try to execute it directly in MySQL to see if it works, or if it generates an error.

Categories