Passing NULL from PHP to MySQL for auto increment - php

So I have a database setup in MySQL with three columns. The first column is 'idnum' that auto increments the users id numbers. The second and third are first and last names respectfully. My problem is when I go to send the the names to the DB via a query string in my PHP file, I get a couple different errors back...
When I send the query:
$sql = "insert into namesdb values('NULL', 'firstname', 'lastname')";
$result = $db->query($sql);
I get back this error: "Incorrect integer value: 'NULL' for column 'idnum' at row 1." Because column 1 is an INT type.
But then when I send this query:
$sql = "insert into namesdb values(".NULL.", 'firstname', 'lastname')";
$result = $db->query($sql);
I get back a syntax error...
Any idea on what the heck I'm doing wrong here??
Thank you for any help!

It should be:
$sql = "insert into namesdb values(NULL, 'firstname', 'lastname')";
$result = $db->query($sql);
'NULL' is a string of "NULL".
Though another option (the one I would go with) is to list the columns explicitly:
INSERT INTO namesdb (firstname, lastname) VALUES ('firstname', 'lastname')
I prefer listing the columns because it is more future proof, and it's easier to see what's going on. Imagine if columns are rearranged, added, or removed in the future. Suddenly fixing your queries is going to be a massive pain if you have to remove the 6th unnamed parameter everywhere (for example).

Its better specify field names which you want to insert and dont specify id field
like
insert into namesdb(firstname,lastname) values('firstname', 'lastname')
It will auto increment your id field

You can write query this way to avoid that problem..
$sql = "INSERT INTO table_name SET column_name_1 = 'value_1', column_name_2 = 'value_2'";

$sql = "insert into namesdb values('NULL', 'firstname', 'lastname')";
In the above query 'NULL' is a string object and your column is an Integer so the error.
$sql = "insert into namesdb values(".NULL.", 'firstname', 'lastname')";
In this query you are sending php NULL value so the final query looks like the following
"insert into namesdb values(, 'firstname', 'lastname')";
So it is invalid.
The correct way to insert should be like this
$sql = "insert into namesdb values(NULL, 'firstname', 'lastname')";
or like this
$sql = "insert into namesdb values('firstname', 'lastname')";
The reason above query works is because of the auto increment.

Related

Fetching last inserted ID and using it as a parameter with PHP/MySQL

I'm very new to PHP, trying to figure things out.
I have the following php code:
$read_more = '[read more]';
$sql = "INSERT INTO database (date, headline, article, read_more) VALUES ('$_POST[date]', '$_POST[headline]', '$_POST[article]', '$read_more')";
The code is returning "http://www.example.com/index.php?id=0". Note that the "id" parameter is returning "0". My goal is to make it return the latest ID from the database, which is set to auto increment.
I've tried many things but nothing worked for me so far. Thanks!
EDIT: After hours of trial and error, this is how I was able to solve this problem:
//After connecting to the database
$sql = "INSERT INTO table (date, headline, article, read_more) VALUES ('$_POST[date]', '$_POST[headline]', '$_POST[article]', '$read_more')";
$result = mysqli_query($conn, $sql);
$id = mysqli_insert_id($conn);
Now the latest id is saved into a variable that I can use.
Try something like this instead. Check the documentation here.
// insert a datarow, primary key is auto_increment
// value is a unique key
$query = "INSERT INTO test (value) VALUES ('test')";
mysql_query( $query );
echo 'LAST_INSERT_ID: ',
mysql_query( "SELECT LAST_INSERT_ID()" ),
'<br>mysql_insert_id: ',
mysql_insert_id();

php date does not posted in the db table

Hi im trying to hard code and set a date to a variable inorder to insert it in db table, but after all my efforts it always prints 0000-00-00 00:00:00. data type in the date column of the table is just datetime
following is the code i tried
$retval = '2007-04-19 12:50:00';
$str_cols = "gmid, panelID, trackerID, timestamp";
$str_values ="$gmid, $panel_id, $track, $retval";
$table = "tracktable_".$track;
$query = "INSERT INTO $table ($str_cols) VALUES ($str_values)";
can any body help on this to get the assigned date in the db table
timestamp is a keyword so it should be in apostrophe like 'timestamp'.
$query = "INSERT INTO ".$table." (`gmid`, `panelID`, `trackerID`, `timestamp') VALUES ('".$gmid."', '".$panel_id."', '".$track."', '".$retval."')";
For it to function surely. Add backticks to your $table. Also there is no single quotes in your values. Use this for sure it will work.
$query = "INSERT INTO `$table` (gmid, panelID, trackerID, timestamp) VALUES ('$gmid', '$panel_id', '$track', '$retval')";
$query = "INSERT INTO ".$table." (`gmid`, `panelID`, `trackerID`, `timestamp`) VALUES ('".$gmid."', '".$panel_id."', '".$track."', '".$retval."')";
Try
$str_cols = "gmid, panelID, trackerID, `timestamp`";
$str_values ="$gmid, $panel_id, $track, '$retval'";

How to insert Integer value in DB - 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();

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');

Categories