Cannot 'insert into' with variables in php - php

Great, now I can 'insert' into the database, but in phpmyadmin the fields are white, without content... This is the php code:
$name = $_POST["name"];
$institution = $_POST["institution"];
$email = $_POST["email"];
$country = $_POST["country"];
$hcp = $_POST["hcp"];
$texto = $_POST["texto"];
$state = $_POST["state"];
$license = $_POST["license"];
$consulta = ("INSERT INTO `1264`(`name`,`institution`,`email`,`country`,`hcp`,`texto`,`state`,`license`) VALUES ('$name','$institution','$email','$country','$hcp','$texto','$state','$license');");
mysql_query($consulta,$connection) or die("You cannot register. Try it later, please.");
Does anybody know why?

Please change your query
you have extra ',' both after 'license' and '$license'
$consulta = ("INSERT INTO `1264`(`id`,`name`,`institution`,`email`,`country`,`hcp`,`texto`,`state`,`license`) VALUES (NULL, '$name','$institution','$email','$country','$hcp','$texto','$state','$license');");
mysql_query($consulta,$connection) or die("You cannot register. Try it later, please.");
Also try using mysqli_* functions. mysql_* functions going to deprecated.

Try this:
$consulta = ("INSERT INTO `1264`(`id`,`name`,`institution`,`email`,`country`,`hcp`,`texto`,`state`,`license`) VALUES (NULL, '$institution','$email','$country','$hcp','$texto','$state','$license');");
ie, remove the extra comma at the last

Dont make the query so clumpsy. Here is a simple edit,
$consulta = "INSERT INTO `1264` SET
`name` = '$name',
`institution` = '$institution',
`email` = '$email',
`country` = '$country',
`hcp` = '$hcp',
`texto` = '$texto',
`state` = '$state',
`license` = '$license'";
You don't have to write the id and leave its value field null, it will be auto generated by default.

if id is an primary key then it should not be null
and if it is an auto increment field have no need to put it on field list and value
$consulta = ("INSERT INTO 1264(name,institution,email,country,hcp,texto,state,license,) VALUES ( '$name','$institution','$email','$country','$hcp','$texto','$state','$license',);");
do echo $consulta ;
to check if the query is coming properly or try put the variables out of cote check the name one
VALUES ( '".$name."','$institution','$email','$country','$hcp','$texto','$state','$license',)

This should work - enter each variable between quotes, especially when its a string
$consulta = ("INSERT INTO `1264`(`id`,`name`,`institution`,`email`,`country`,`hcp`,`texto`,`state`,`license`) VALUES (NULL, "'. $name ."','".$institution."','".$email."','".$country."','".$hcp.'","'.$texto.'","'.$state.'",'".$license."');");

Removed the last comma and Id -> NULL so try this:
`$consulta = ("INSERT INTO` `1264`(`name`,`institution`,`email`,`country`,`hcp`,`texto`,`state`,`license`) VALUES `('$name','$institution','$email','$country','$hcp','$texto','$state','$license');");

Related

MySql: Insert values in an auto_increment field with PHP

What I'm actually trying to do is insert a row with:
INSERT INTO users VALUES (col1, col2, ...)
where col1 is an auto_increment.
The PHP code is:
<?php
$host = "http://name.altervista.org/";
$user = "name";
$psw = "";
$db = "my_name";
$response = array();
$response["success"] = true;
$connessione = new mysqli($host, $user, $psw, $db);
if($connessione->connect_errno == 0)
{
$nome = $_POST["nome"];
$cognome = $_POST["cognome"];
$username = $_POST["username"];
$password = $_POST["password"];
$nTelefono = $_POST["nTelefono"];
$email = $_POST["email"];
$sql = "INSERT INTO users
VALUES (DEFAULT, '$nome', '$cognome', '$username', '$password', '$nTelefono', '$email')";
$ris = $connessione->query($sql);
if($connessione->affected_rows == 1)
{
echo(json_encode($response));
}
else
{
$response["success"] = false;
echo(json_encode($response));
}
}
else
{
$response["success"] = false;
echo(json_encode($response));
}
?>
I search similar questions here in stackoverflow, and I try to use DEFAULT or NULL, but it doesn't work. And if I put a number instead of the default value that is not already in the table it works, so I really don't understand where the problem is.
Have you any other suggestions?
EDIT: The table structure on the database:
click
EDIT 2: I tried to delete the table and create it again, and now it works with the NULL thing. Thanks for the support!
When you are doing an insert, list all the columns being inserted. You seem to want:
INSERT INTO users (nome, cognome, username, password, nTelefono, email)
VALUES ('$nome', '$cognome', '$username', '$password', '$nTelefono', '$email');
Next. Never store clear-text passwords in the database. You should be encrypting the value on the client side so the values are never passed over the network.
Next. Learn to use parameterized queries. When you munge query strings with parameter values, your are asking for inexplicable syntax errors and making the code subject to SQL injection attacks.
From the Mysql docs
INSERT INTO users VALUES ('$nome', '$cognome', '$username', '$password', '$nTelefono', '$email')";
The auto_increment fields doesn't need to be set in an INSERT statement
In MySQL, if you have an auto_increment column you don't need to put it in the insert statement.
Example:
You have the table:
CREATE TABLE test (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL
);
Your SQL statement should be:
INSERT INTO test(name) VALUES ('My name');

Basic , Sending data to database, PHP

I'm new to PHP and so far I've managed to connect to my database, but when I try to send data to the database I don't get any script errors, but the data doesn't go through and I receive the message "Succesfully Created User!", which basically means the data has been sent right?
Here is my script:
<?php
$user = $_POST['user'];
$name = $_POST['name'];
$pass = $_POST['password'];
$con = mysql_connect("fdb13.awardspace.net", "myusername", "mypassword") or die(mysql_error());
if(!$con)
die('Could not connectzzz: ' . mysql_error());
mysql_select_db("myusername" , $con) or die ("could not load the database" . mysql_error());
$check = mysql_query("SELECT * FROM unitytut WHERE `user`='".$user."'");
$numrows = mysql_num_rows($check);
if($numrows == 0)
{
$pass = md5($pass);
//$ins = "INSERT INTO unitytut (user, name, pass) VALUES ('John', 'Doe', 'John');";
//$ins = ("INSERT INTO `unitytut` (`user`), (`name`), (`pass`) VALUES ('' , 'John', 'Doe', 'John''John', 'Doe', 'John') ; ");
$ins = ("INSERT INTO `unitytut` (`user`), (`name`), (`pass`) VALUES ('' , '".$user."' , '".$name."', '".$pass."') ; ");
if($ins)
die("Succesfully Created User!");
else
die("ERROR");
}
else
{
die("user already exists!");
}
?>
I've tried several insert methods, but the only 3 functions that didn't receive the "ERROR" message was:
$ins = mysql_query("INSERT INTO unitytut (`user`), (`name`), (`pass`) VALUES ('' , '$user' , '$name', '$pass')" ) ;
and
$ins = ("INSERT INTO `unitytut` (`user`), (`name`), (`pass`) VALUES ('' , 'John', 'Doe', 'John''John', 'Doe', 'John') ; ");
and
$ins = ("INSERT INTO `unitytut` (`user`), (`name`), (`pass`) VALUES ('' , '".$user."' , '".$name."', '".$pass."') ; ");
I also have an ID in my table, but as I've been researching this issue without managing to fix it, I also read that I don't need to specify the ID in the script as the user is getting an ID automatically, but as I haven't gotten this to work I wouldn't know for sure.
I'm very new to php and databases in general, but I've been stuck on this for a while now, so any help would be greatly appreciated :)
Also any feedback on the way I posted this is also welcome, did I give you too much information, too many questions in one post, too much text etc.?
Thanks!
You should format your INSERT statement like this:
$ins = mysql_query("INSERT INTO unitytut (`user`,`name`,`pass`) VALUES ('$user' , '$name', '$pass')" ) ;
However, mysql_query is deprecated, See this link and follow it's advice on using a newer extension

How to insert Null value to INT in mysql

I have one field name is "owner". It is a foreign key Value. Initially i defined NULL value.
In PHP,
if($memberType=='owner'){
$ownerId = "";
}else{
$ownerId = $_POST['ownerId'];
}
$sql_user = mysqli_query($con,"INSERT INTO user(firstname, lastname,owner_id) VALUES ('$fname', '$lname', '$ownerId')");
Here Data is not inserting. When i remove owner_id during inserting, It is working.
How to define Null value to that
Your sql is fine. edit column in mysql, remove NOT NULL in the column.
$ownerId=0;
if($memberType=='owner'){
$ownerId = $_POST['ownerId'];
}
$sql_user = mysqli_query($con,"INSERT INTO user(firstname, lastname,owner_id) VALUES ('$fname', '$lname', '$ownerId')");

How to put Null value in a SQL sever via php code

I have the following code, which will get values from these 9 variables and insert them in to a table. However, I don't know how to insert NULL value in to my table. As shown in line 10, if I try to use the keyword NULL, it consider as a string.
$WorkOrder = $_POST['WorkOrder'];
$Originated = $_POST['Originated'];
$CustID = $_POST['CustID'];
$Customer = $_POST['Customer'];
$Contact = $_POST['Contact'];
$Completed = $_POST['Completed'];
$AccountNum = $_POST['AccountNum'];
$Description = $_POST['Description'];
$Status = $_POST['Status'];
$Status = "NULL"; //Testing with NULL
$insertquery = "INSERT INTO ElectronicShop(WorkOrder, Originated, CustID, Customer, Contact, Completed, AccountNum, Description, Status)
VALUES ('$WorkOrder','$Originated','$CustID','$Customer','$Contact','$Completed','$AccountNum','$Description','$Status')";
$data = sqlsrv_query($connectString, $insertquery) or die(print_r(sqlsrv_errors(SQLSRV_ERR_ALL), true));
I will be getting values for these 9 variables via text boxes in a webpage. So, I can't manually enter NULL in my query.
Instead of:
$insertquery = "INSERT INTO ElectronicShop(WorkOrder, Originated, CustID, Customer, Contact, Completed, AccountNum, Description, Status) VALUES ('$WorkOrder','$Originated','$CustID','$Customer','$Contact','$Completed','$AccountNum','$Description','$Status')";
Use:
$insertquery = "INSERT INTO ElectronicShop(WorkOrder, Originated, CustID, Customer, Contact, Completed, AccountNum, Description, Status) VALUES
('$WorkOrder','$Originated','$CustID','$Customer','$Contact','$Completed','$AccountNum','$Description', NULL)";
You don't need to specify a variable for it, just write "NULL" without string marking signs (') into your query.
Greetz
Don't use the qoutes "":
$Status = "NULL";
Use:
$Status = null;
If you have not default value for Status column another than NULL, simply do not use this column in the columns list of insert statement.

inserting form data into mysql fails when using CURRENT_TIMESTAMP?

I am trying to insert the data from my form into mysql, this works fine but when i add a 'date_created' column with TimeStamp and CURRENT_TIMESTAMP it causes the sql query to fail?
Can anyone tell me why this is?
Here's my mysql function:
<?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'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$country = $_POST['country'];
$query="INSERT INTO ptb_registrations (ID,
username,
password,
firstname,
lastname,
email,
age,
gender,
country
)
VALUES('NULL',
'".$username."',
'".$password."',
'".$firstname."',
'".$lastname."',
'".$email."',
'".$age."',
'".$gender."',
'".$country."'
)";
mysql_query($query) or die ('Error updating database');
?>
<?php include ('send_email/reg_email.php'); ?>
<? ob_flush(); ?>
you can try this to add date/time column to your table. then try again to insert the query and see if it works:
ALTER TABLE table_name ADD timeanddate_colname TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
if your column is not timestamp then alter your table like that
ALTER TABLE table_name ADD DEFAULT (CURRENT_TIMESTAMP) FOR [Cold2]
or there is other cases if you can add curent_date by CURDATE() or NOW()

Categories