How to insert Integer value in DB - PHP - php

I have using PHP for inserting integer value in Database.
Iam using like this
$postcode = $_POST['postcode'];
$mysql_user_resultset = mysqli_query($con, "INSERT into user (postcode) VALUES ($postcode)");
I have several field in DB. like name, username, etc. all are defined as varchar, but postcode only defined as int. If not enter the value for postcode, it doesn't insert into database

You could simply cast your variable into int:
$postcode = (int) $_POST['postcode'];
$mysql_user_resultset = mysqli_query($con, "INSERT into user (postcode) VALUES ($postcode)");
Note that you're not using any precautions regarding SQL injections, I would suggest you to bind your parameters before query them, using PDO class.

Convert $_POST['postcode'] to int, using
$postcode = (int)$_POST['postcode'];

Use PDO or sprintf for formatting mysql query:
sprintf example:
$mysql_user_resultset = mysqli_query($con, sprintf(
"INSERT into user (postcode) VALUES (%d)",
$_POST['postcode']));
PDO example:
$st = $db->prepare("INSERT into vendors user (postcode) VALUES (:postcode)");
$st->bindParam(':postcode', $_POST['postcode'], PDO::PARAM_INT);
$mysql_user_resultset = $st->execute();

Related

SQL - Insert INTO results in nothing

I've been trying to get this INSERT to work correctly, so I worked through the undefined variable and index problems and now I think I am nearly there.
Below is the code:
<?php
session_start();
require "../dbconn.php";
$username = $_SESSION['username'];
$query1 = "SELECT user_table.user_id FROM user_table WHERE user_table.username ='".$username."'";
$query2 = "SELECT department.department_id FROM department, user_table, inventory
WHERE user_table.user_id = department.user_id
AND department.department_id = inventory.department_id";
//Copy the variables that the form placed in the URL
//into these three variables
$item_id = NULL;
$category = $_GET['category'];
$item_name = $_GET['item_name'];
$item_description = $_GET['item_description'];
$item_quantity = $_GET['quantity'];
$item_quality = $_GET['quality'];
$item_status = NULL;
$order_date = $_GET['order_date'];
$invoice_attachment = NULL;
$edit_url = 'Edit';
$ordered_by = $username;
$user_id = mysql_query($query1) or die(mysql_error());
$department_id = mysql_query($query2) or die(mysql_error());
$price = $_GET['price'];
$vat = $_GET['vat%'];
$vat_amount = $_GET['vat_amount'];
$create_date = date("D M d, Y G:i");
$change_date = NULL;
//set up the query using the values that were passed via the URL from the form
$query2 = mysql_query("INSERT INTO inventory (item_id, category, item_name, item_description, item_quantity, item_quality, item_status, order_date,
invoice_attachment, edit_url, ordered_by, user_id, department_id, price, vat, vat_amount, create_date, change_date VALUES(
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$item_quantity."',
'".$item_quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$user_id."',
'".$department_id."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
header( 'Location:../myorders.php');
?>
Error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'VALUES( '', 'adasd', 'dsadsa', 'dsad', 'sadsad', '' at line 2
Could anyone please let me know where I am going wrong? :(
Been staring at this for 3-5 hours already :(
You are not actually trying to insert any data into your table. You only craft and assign the query in string form to a variable. You need to use the function mysql_query to actually run the code.
As pointed out you will also have to specify the columns you are inserting data into in the MySQL query if you don't supply data for every column (in the correct order). Here you can look at the MySQL insert syntax.
I would also urge you to look into using the MySQLi or the MySQL PDO extensions for communicating with your MySQL database since the MySQL extension is deprecated. Look here for additional information and comparisons.
Here, you only assign the values to the $query var:
$query = "INSERT INTO inventory VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')"
or die("Error: ".mysql_error());
You do not actually run the query.
try:
$query = mysql_query("INSERT INTO inventory (column_name1, column_name 2, column_name3 ... the column name for each field you insert) VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
Also, you should use mysqli_* or any other PDO as the mysql_* functions are deprecated
If you are not inserting in all columns you need to specify the columns you are going to insert. Like this:
INSERT INTO Table(Column1, Column6) VALUES (Value1, Value6)
You are missing the column names in your INSERT

INSERT INTO TABLE .. php - variable in sql query

I have php script containing following SQL query (working oK):
$query = 'INSERT INTO persons'.
'(name,
surname
)'.'VALUES
( "'.$_REQUEST["name"].'",
"'.$_REQUEST["surname"].'"
)';
Where $_REQUEST["name"] and $_REQUEST["name"] are variables passed from html form.
usin php 4.5 and MariaDB 5.5
Problem rises when i try to substitute persons by variable - eg. $table:
$table = "persons";
$query = 'INSERT INTO '.$table.''.
'(name,
surname
)'.'VALUES
( "'.$_REQUEST["name"].'",
"'.$_REQUEST["surname"].'"
)';
I have been trying different variations with double qutes/single qutes/dots :). But still struggling with this..
Thx for possible answer.
Its a simply case of knowing how the single and double quote works in PHP
Try this
$table = 'persons';
$query = "INSERT INTO $table (name,surname)
VALUES ( '{$_REQUEST['name']}',
'{$_REQUEST['surname']}' )";
Now of course you should not be using the mysql_* extension anymore but if you have to you should at least try and sanitize the input values before you use them
So the code becomes
// do at least this to sanitize the inputs
$_REQUEST['name'] = mysql_real_escape_string($_REQUEST['name']);
$_REQUEST['surname'] = mysql_real_escape_string($_REQUEST['surname']);
$query = "INSERT INTO $table (name,surname)
VALUES ( '{$_REQUEST['name']}',
'{$_REQUEST['surname']}' )";
$table_name = 'persons';
$query = "insert into ".$table_name." (name,surname) values ('".$_REQUEST['name']."','".$_REQUEST['surname']."') ";

Php pdo insert query

I need to insert encrypted values in mysql table, but when I use traditional pdo method to insert its inserting the data in wrong format. ex: I insert aes_encrypt(value, key) in place of inserting encrypted value its inserting this as string.
Following is the code :
$update = "insert into `$table` $cols values ".$values;
$dbh = $this->pdo->prepare($update);
$dbh->execute($colVals);
$arr = array("col"=>"aes_encrypt ($val, $DBKey)");
I know i am doing it wrong, but not able to find correct way.
You are almost there, here is a simplified version:
<?php
$sql = "insert into `users` (`username`,`password`) values (?, aes_encrypt(?, ?))";
$stmt = $this->pdo->prepare($sql);
// Do not use associative array
// Just set values in the order of the question marks in $sql
// $fill_array[0] = $_POST['username'] gets assigned to first ? mark
// $fill_array[1] = $_POST['password'] gets assigned to second ? mark
// $fill_array[2] = $DBKey gets assigned to third ? mark
$fill_array = array($_POST['username'], $_POST['password'], $DBKey); // Three values for 3 question marks
// Put your array of values into the execute
// MySQL will do all the escaping for you
// Your SQL will be compiled by MySQL itself (not PHP) and render something like this:
// insert into `users` (`username`,`password`) values ('a_username', aes_encrypt('my_password', 'SupersecretDBKey45368857'))
// If any single quotes, backslashes, double-dashes, etc are encountered then they get handled automatically
$stmt->execute($fill_array); // Returns boolean TRUE/FALSE
// Errors?
echo $stmt->errorCode().'<br><br>'; // Five zeros are good like this 00000 but HY001 is a common error
// How many inserted?
echo $stmt->rowCount();
?>
you can try it like this.
$sql = "INSERT INTO $table (col) VALUES (:col1)";
$q = $conn->prepare($sql);
$q->execute(array(':cols' => AES_ENCRYPT($val, $DBKey)));

Trying to update column value for specific row only?

I am having some problems with a script, I am basically inputting data into a MySQL table. This data will be inserted in the table as 1 row.
Upon a row of data being entered into the table I want the current/specific row currently being entered to have the column 'account_type' to be updated from its default value 'member' to 'client'.
It's a long story why I need to do it this way but I do not want to simply just enter the value 'client' it must be updated from 'member' to client.
The script I have (which is the bit at the bottom) is currently doing just this but it is affecting all rows in the table, is there a way I can add a where clause to the update to say only affect the current row being entered and do not update all other rows in the table?
<?php ob_start();
// CONNECT TO THE DATABASE
require('../../includes/_config/connection.php');
// LOAD FUNCTIONS
require('../../includes/functions.php');
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$number = $_POST['number'];
$dob = $_POST['dob'];
$accounttype = $_POST['accounttype'];
$query="INSERT INTO ptb_registrations (
username,
password,
firstname,
lastname,
email,
number,
dob,
accounttype,
date_created )
VALUES(
'".$username."',
'".$password."',
'".$firstname."',
'".$lastname."',
'".$email."',
'".$number."',
'".$dob."',
'".$accounttype."',
now()
)";
mysql_query($query) or die();
$query="INSERT INTO ptb_users (
first_name,
last_name,
email,
password )
VALUES(
'".$firstname."',
'".$lastname."',
'".$email."',
MD5('".$password."')
)";
mysql_query($query) or dieerr();
$result = mysql_query("UPDATE ptb_users SET ptb_users.user_id = ptb_users.id,
ptb_users.account_type = 'Client'");
Please, don'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.
You can use the MySQL function LAST_INSERT_ID() to do this.
The old ext/MySQL extension exposes this functionality through mysql_insert_id(), but you can also access it directly, and more cleanly, and safely, in a query.
So you can do something like this:
$result = mysql_query("
UPDATE ptb_users
SET ptb_users.user_id = ptb_users.id,
ptb_users.account_type = 'Client'
WHERE id = LAST_INSERT_ID()
");
I know you say "it's a long story..." But what you are doing makes little-to-no sense. I can only imagine you are doing this because of a trigger - and that demonstrates quite nicely why triggers are generally a bad idea ;-)
Please try and re-think your design if at all possible.
Get the inserted ID after your first query then use it in the update (assuming you have a primary key with auto-increment).
Try With WHERE Condition on unique coloumn
mysql_query("UPDATE ptb_users SET ptb_users.user_id = ptb_users.id,
ptb_users.account_type = 'Client'" WHERE ptb_user.email='$email');

Form is submitting empty values to database

After being advised that i MUST validate my form so that no-one could hack my database i then made some changes which were adding the mysql_real_string()
$query="INSERT INTO allymccoist (id, firstname, lastname, email, date)
VALUES (NULL, '".$firstname."', '".$lastname."', '".$email."', '".mysql_real_escape_string($new_date)."')";
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$email = mysql_real_escape_string($_POST['email']);
$datepicker = mysql_real_escape_string($_POST['date']);
since doing this, nothing is being sent to firstname lastname or email although the date seems to be sending ok though
is thereanything that may be causing this that you can see from my code?
If you're sure that those data actually are set (var_dump your $_POST array to check that),then make sure you have a connection active before using mysql_real_escape_string(), as it would return FALSE otherwise:
A MySQL connection is required before using mysql_real_escape_string()
otherwise an error of level E_WARNING is generated, and FALSE is
returned. If link_identifier isn't defined, the last MySQL connection
is used.
So you can well be entering FALSE in every value.
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')or die(mysql_error());
mysql_select_db('database_name', $link) or die('cannot select database '.mysql_error());
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$email = mysql_real_escape_string($_POST['email']);
$datepicker = mysql_real_escape_string($_POST['date']);
You'd be better off altogether by using prepared statements, so you won't have to worry about SQL injections.
Also, I'd advice you against using NULL in your insert query for the field ID. If you're table is strcutred as I can guess, and ID is a primary key with AutoIncrement, you don't need to enter it in your query, as it would be automatically filled by the engine.
For wheter it is better to use prepared statements or mysql_real_escape_string(), check this resource mysql_real_escape_string vs prepared statements
The issue of missing data is likely as Damien suggests. Establish a connection, then use mysql_real_escape_string(). The connection is required in part so that mysql_real_escape_string() can take into account the current character set of the connection.
Also, mysql_real_escape_string() is perfectly safe when used in combination with the sprintf() function (full details on sprintf). Most important with sprintf() is setting the correct type specifier so that values get cast properly. Generally, for integers you will use %d. For floats use %f. And for string and date values use %s.
So for your program the code should look something like (note: as Damien suggests, leave id out of the query):
/* Read form data. */
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$email = $_POST['email'];
$date = $_POST['date']);
/* Your form validation code here. */
/* Your db connection code here. */
/* Setup and run your query. */
$query = sprintf("INSERT INTO allymccoist (firstname, lastname, email, date)
VALUES ('%s', '%s', '%s', '%s')",
mysql_real_escape_string($firstName),
mysql_real_escape_string($lastName),
mysql_real_escape_string($email),
mysql_real_escape_string($date));
$result = mysql_query($query);
/* Check for errors with query execution. */
if (!$result) echo("Query Error! Process aborted.");

Categories