Insert Into Mysql DB - php

I am having a small issue with some coding of mine. For some reason my entries aren't dropping in my DB. Any suggestions would be greatly appreciated! Here is my code...
<?php
$dbhost="localhost";
$dbname="DBNAME";
$dbuser="USER";
$dbpasswd="PASSWORD"; // connect to the db
$dbcxn = mysqli_connect($dbhost, $dbuser, $dbpasswd);
if (!$dbcxn) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysqli_select_db($dbcxn, $dbname);
if (!$db_selected) {
die ('Can\'t use dbreviews : ' . mysql_error());
}
$query = "INSERT INTO entries ( submitterFirstName, submitterLastName, submitterPhone, submitterEmail, referredFirstName, referredLastName, referredPhone, referredEmail, referredReason)
VALUES ('$submitterFirstName', '$submitterLastName', '$submitterPhone', '$submitterEmail', '$referredFirstName', '$referredLastName', '$referredPhone', '$referredEmail', '$referredProject')";
$result=mysqli_query($dbcxn, $query);
?>

The first thing you want to check is echo the query back to yourself and read it over.
Second, check the table structure. Make sure the column names are all spelled correctly and that all fields exist in your table (I've accidently forgotten to add a column before).
Third, you may or may not receive error messages depending on your configuration. But, you can manually check.
if (!$result) {
echo mysqli_error($dbcxn);
}

First thing first should be code formatting, it will help you read the code and consequently find your errors easier.
$query = "
INSERT INTO
entries
(
submitterFirstName,
submitterLastName,
submitterPhone,
submitterEmail,
referredFirstName,
" .
"referredLastName,
referredPhone,
referredEmail,
referredReason
)
" .
" VALUES
(
'$submitterFirstName',
'$submitterLastName',
'$submitterPhone',
' $submitterEmail',
'$referredFirstName'," .
"'$referredLastName',
'$referredPhone',
'$referredEmail',
'$referredProject'
);
"
The above is your query string split onto several lines, there are some errors which should be evident straight away? Once formatted I would do echo $query and view the output of $query.
Also try seeing if you can do an insert without using php (using mysql workbench, php admin etc) then compare it with the string value you have set as $query.
// less errors, please note that inside "" you can include php $vars without needing to escape.
$query = "
INSERT INTO
entries
(
submitterFirstName,
submitterLastName,
submitterPhone,
submitterEmail,
referredFirstName,
referredLastName,
referredPhone,
referredEmail,
referredReason
)
VALUES
(
'$submitterFirstName',
'$submitterLastName',
'$submitterPhone',
'$submitterEmail',
'$referredFirstName',
'$referredLastName',
'$referredPhone',
'$referredEmail',
'$referredProject'
);
";

Change your query variable to:
$query = "INSERT INTO entries " .
"( submitterFirstName, submitterLastName, submitterPhone, submitterEmail, referredFirstName, " .
" referredLastName, referredPhone, referredEmail, referredReason )" .
" VALUES ('" .
$submitterFirstName . "', '" .
$submitterLastName . "', '" .
$submitterPhone . "', '" .
$submitterEmail . "', '" .
$referredFirstName . "', '" .
$referredLastName . "', '" .
$referredPhone . "', '" .
$referredEmail . "', '" .
$referredProject . "')";
and it should be working.
Suggesting to use mysqli prepare

Related

I am attempting to switch from mysql to mysqli and cannot see why there is a error on else statement

I have included the php code run on the server side that is failing with the following error:
Parse error: syntax error, unexpected T_ELSE in
/home3/atljj/public_html/Osler/include/vo2_membersite.php on line 2849
No clue why it is stopping on the ELSE statement ???
Short story... I want to write a program to create and maintain a 1 record MYSQL control file.
I am writing the code in steps and so far have:
Written HTML code to via a form, submit to the server a request to create the table with the proper fields.
The server was then re-written to write the first record into the table via the INSERT statement.
All is well to this point... I have 1 record in the MySQL file and next I only need to update it.
The server was changed to test for a record already existing and if so bypass the INSERT code and run the UPDATE code instead... But I do not see where the problem is, other than I am attempting to use MYSQLi code now.
Is my table checking done wrong, I'm searching for record 1 and if not found use INSERT ELSE use the UPDATE...
function UpdateCase(&$formvars)
{
$con = mysqli_connect($this->db_host,$this->username,$this->pwd,$this->database);
if (mysqli_connect_errno())
{
$this->HandleDBError("Failed to connect to MySQL");
return false;
}
$c_match = $this->RandomIt();
$c_username = "admin";
$qry = "Select * from $this->case_c_table WHERE c_id = 1";
if(!$result = mysqli_query($con,$qry));
{ /* first entry not found add to table*/
$c_flag="M";
$addit = 'INSERT INTO $this->case_c_table (
c_match,
c_flag,
c_username,
c_element,
c_patname,
c_patgndr,
c_patage,
c_patethncty,
c_patdate,
c_cc,
c_td,
c_lmpdate
)
values
(
"' . $c_match . '",
"' . $c_flag . '",
"' . $c_username . '",
"' . $this->SanitizeForSQL($formvars['c_element']) . '",
"' . $this->SanitizeForSQL($formvars['c_patname']) . '",
"' . $this->SanitizeForSQL($formvars['c_patgndr']) . '",
"' . $this->SanitizeForSQL($formvars['c_patage']) . '",
"' . $this->SanitizeForSQL($formvars['c_patethncty']) . '",
"' . $this->SanitizeForSQL($formvars['c_patdate']) . '",
"' . $this->SanitizeForSQL($formvars['c_cc']) . '",
"' . $this->SanitizeForSQL($formvars['c_td']) . '",
"' . $this->SanitizeForSQL($formvars['c_lmpdate']) . '"
)';
mysqli_query($con,$addit);
}
else
{
$qry="Update $this->case_c_table Set
c_element=". $this->SanitizeForSQL($formvars['c_element']).",
c_patname=". $this->SanitizeForSQL($formvars['c_patname']).",
c_patgndr=". $this->SanitizeForSQL($formvars['c_patgndr']).",
c_patage=" . $this->SanitizeForSQL($formvars['c_patage']).",
c_patethncty=". $this->SanitizeForSQL($formvars['c_patethncty']).",
c_patdate=". $this->SanitizeForSQL($formvars['c_patdate']).",
c_cc=". $this->SanitizeForSQL($formvars['c_cc']).",
c_td=". $this->SanitizeForSQL($formvars['c_td']).",
c_lmpdate=". $this->SanitizeForSQL($formvars['c_lmpdate'])."
WHERE c_id=1";
mysqli_query($con,$qry);
}
}

Calling user defined functions in php for mysql query

Hi I'm trying to call several functions that I have defined in php within mysql_query. The sql query executes successfully however all the columns which should contain values from functions are left empty in the database. The sql query looks like this:
$sqldescription = description($e->href);
$sqlimage = image($e->href,$e->innertext);
$sqlstatus = status($e->href);
$sqlgenre = genre($e->href);
$sqlauthor = author($e->href);
$sqlrelease = release($e->href);
$sql = "INSERT INTO manga (`manga_title`, `manga_description`, `manga_thumnail`, `manga_latest_chap`, `manga_status`, `manga_genre`, `manga_author`, `manga_released_date`, `manga_added_date`, `manga_link`) VALUES
('" . $e->innertext . "', '" . $sqldescription . "', '$sqlimage', '0', '$sqlstatus', '$sqlgenre', '$sqlauthor', '$sqlrelease', '" . date("Y-m-d") . "', '" . $e->href . "')";
mysql_query($sql,$con);
most of the functions are pretty similar and here is what one of them looks like:
function description($url){
$descriptionhtml = new simple_html_dom();
$descriptionhtml->load_file($url);
foreach ($descriptionhtml->find('p.summary') as $d)
echo $d;
}
I would appreciate any help :)

Querying using array

There is nothing wrong with my code, but I just cant help but wonder, should I wrap the $key with mysql_real_escape_string? This is just part of my Database function which is mainly used to pull data out of the database with table name and $where as arguments to the function. $where is to be an associative array with keys being column name, and values being the data.
This is what processes the $where array. Before this I have $sql = 'select * from ' . $table;
if(!empty($where)){
$where_count = count($where);
$sql .= ' WHERE ';
foreach($where as $key => $value){
$split_key = explode(' ', $key);
if(count($split_key) > 1){
$sql .= $key[0] . ' ' . $key[1] . ' "' . mysql_real_escape_string($value) . '" ';
} else {
$sql .= $key . ' = "' . mysql_real_escape_string($value) . '" ';
}
}
}
Filter ANY INPUT from the user that is going to be placed in your query. No doubt!
So if the keys are supplied by the user, YES and if they are generated in a safe manner, NO.
Take a look at SQL Injection to understand why filtering must be done.
I am not sure what is being asked here, but I can see one error:
$sql .= $key[0] . ' ' . $key[1] . ' "' . mysql_real_escape_string($value) . '" ';
should be
$sql .= $split_key[0] . ' ' . $split_key[1] . ' "' . mysql_real_escape_string($value) . '" ';
If you really want to quote field names, use backticks.
See http://dev.mysql.com/doc/refman/5.6/en/identifiers.html
The following statement creates a table named a`b that contains a
column named c"d:
CREATE TABLE `a``b` (`c"d` INT);

Combining two PHP variables for MySQL query

I have a variable formvar that is incremented every time a user adds an additional field in an HTML form. This variable is posted to the PHP script for the purpose of looping through all of the added fields.
I am trying to combine two variables in the MySQL query to match what is in my HTML form. I would like the MySQL query to go upc0, upc1, etc until the for loop terminates.
for($i=0;$i<=$_POST[formvar];$i++)
{
mysql_select_db("bits", $con);
$sql="INSERT INTO report (UPC, Quantity, Comment)
VALUES ('$_POST[upc].$i','$_POST[quantity].$i','$_POST[comment].$i')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else echo "Records added successfully";
}
Sorry if this code is bad, I am new to web programming.
Thank you!
Ok, since each answer hinted at escaping (but did not give an example):
$sql = "INSERT INTO report (UPC, Quantity, Comment) VALUES
('" . mysql_real_escape_string($_POST["upc".$i]) . "','" .
mysql_real_escape_string($_POST["quantity" . $i]) . "','" .
mysql_real_escape_string($_POST["comment" . $i]) . "')";
That should protect you from SQL Injection, and is one proper method of creating sql queries. The best method would be to use parametrized queries (There's a ton of information out there on it, so I'd suggest a good Google search would be better than me trying to explain it here)...
First things first. In your HTML, create Input-Fields like this:
<input type="foo" name="upc[]">
<input type="foo" name="quantity[]">
<input type="foo" name="comment[]">
Then in your PHP-Script you do it like this:
<?php
# Choose DB
mysql_select_db("bits", $con);
# Iterates the Form-Data
$data_arr = array();
foreach($_POST['upc'] as $k=>$v) {
# Makes sure all needed data is available
if(isset($_POST['quantity'][$k], $_POST['comment'][$k])) {
$data_arr[] = array(
'upc' => $v,
'quantity' => $_POST['quantity'][$k],
'comment' => $_POST['comment'][$k]
);
}
}
# Build mysql insert string
foreach($data_arr as $k=>$v) {
# Escapes each field
$v = array_map('mysql_real_escape_string', $v);
# Maps array to value set
$data_arr[$k] = '('. implode(',', $v). ')';
}
$sql = 'INSERT INTO report (UPC, Quantity, Comment) VALUES '. implode(', ', $data_arr);
# Perform mysql query
mysql_query($sql, $con) or die('Error: ' . mysql_error());
echo 'Records added successfully';
Wrote it on my iPad, i'm on an airplane... so untestet. Good luck. ;o)
Not sure if I understand the question well but this is what I think :
$sql="INSERT INTO report (UPC, Quantity, Comment) VALUES
('" . $_POST["upc".$i] . "','" . $_POST["quantity" . $i] . "','" . $_POST["comment" . $i] . "')";
Note : this is a short version, you must add mysql_real_escape_string, etc, etc.
Also I supposed every variable could be string so I surrounded them by ''.
$_POST["name" . $i] let you loop throught POST variables starting with the name "name" followed by a number, this must be inserted into your for loop.
As recipes are so acclaimed I'm going to give my own, concerning the actual question:
<?php
for ($i=0; $i<=$_POST['formvar']; ++$i) {
mysql_select_db("bits", $con);
$v = array_map(mysql_real_escape_string(array(_POST["upc{$i}"], $_POST["quantity{$i}"], $_POST["comment{$i}"])));
$sql = "INSERT INTO report (UPC, Quantity, Comment) VALUES('"
. implode("', '", $v)
. "')";
if (!mysql_query($sql,$con)) {
trigger_error(html_entities('Error: ' . mysql_error()));
}
}
?>

inserting variable into table

I am able to generate the activation_key in the following code. But I can't manage to insert it into the table. Blank value gets inserted into the table.
What am I doing wrong? (using PEAR text password and other extensions)
$activation_key = Text_Password::createFromLogin($data['email'], 'rot13');
$sql = "INSERT INTO auth (firstname, lastname,gender,dob,mobileno,landlineno,addressline1,addressline2,addressline3,country,state,city,pincode,email,username,password,question,answer,activation_key)
VALUES ('" . $db->escapeSimple($data['firstname']) . "','"
. $db->escapeSimple($data['lastname'])."','"
. $db->escapeSimple($data['gender'])."','"
. $db->escapeSimple($data['dob'])."','"
. $db->escapeSimple($data['mobileno'])."','"
. $db->escapeSimple($data['landlineno'])."','"
. $db->escapeSimple($data['address1'])."','"
. $db->escapeSimple($data['address2'])."','"
. $db->escapeSimple($data['address3'])."','"
. $db->escapeSimple($data['country'])."','"
. $db->escapeSimple($data['state'])."','"
. $db->escapeSimple($data['city'])."','"
. $db->escapeSimple($data['pin'])."','"
. $db->escapeSimple($data['email'])."','"
. $db->escapeSimple($data['username'])."','"
. md5($db->escapeSimple($data['pwd']))."','"
. $db->escapeSimple($data['question'])."','"
. $db->escapeSimple($data['answer']). "', '"
. $db->escapeSimple($data['activiation_key'])."')";
$db->query($sql);
$data['$activiation_key'] doesn't actually appear to hold $activation_key
plus if you really cut and paste then $activiation_key is spelt wrongly

Categories