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
Related
I have a table name "User" writen in MySQL with the fields: UserID, UserName, Password, eMail, DisplayName, Score, timeStamp. The field UserID is int AUTO_INCREMENT and time stamp is dateTime. I'm trying to insert values into the table using php file. This is my php file:
mysql_connect("mysql.1freehosting.com","u948577195_uname","p7CraCuRAw");
mysql_select_db("u948577195_dbnam");
$uName = $_GET['uname'];
$pass = $_GET['password'];
$mail = $_GET['email'];
$disName = $_GET['disnam'];
$date = $_GET['dt'];
$sql=mysql_query("INSERT INTO User
VALUES ('$uName', '$pass', '$mail', '$disName', 0, '$date')");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
I activate the file using this connection string:
http://pickupfriend.fulba.com/android_project/query3.php?uname=Test&password=p1&email=ml&disnam=Test&dt=21:12:30 2014-07-07
I have a space between the seconds and the year in the date, is it OK? After I run the connection string I receive this error:
Parse error: syntax error, unexpected T_STRING in /home/u948577195/public_html/android_project/query3.php on line 13
What am I doing wrong? How to correct my connection string?
Thank you in advance!
Your link shows that you are getting the parameters wrong in the $_GET part.
Hence you must delete this line as it's not php
INSERT INTO [USER]
VALUES ('$uName', '$pass', '$mail', '$disName', 0, '$date')
Change your code as as below.
mysql_connect("mysql.1freehosting.com","u948577195_uname","p7CraCuRAw");
mysql_select_db("u948577195_dbnam");
$uName = $_GET['uname'];
$pass = $_GET['pass'];
$mail = $_GET['mail'];
$disName = $_GET['disName'];
$date = $_GET['date'];
$sql = mysql_query("INSERT INTO User VALUES ('$uName', '$pass', '$mail', '$disName', 0, '$date')");
if (!$sql) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
}
mysql_close();
And your are not fetching anything within your query, if your aim is to see all add this before mysql_close()
$query = mysql_query('SELECT * FROM User');
if (!$query) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
}
$output = array();
while ($row = mysql_fetch_assoc($query) !== false) {
$output[] = $row;
}
echo json_encode($output);
And what do you expect to happen?
INSERT INTO [USER]
VALUES ('$uName', '$pass', '$mail', '$disName', 0, '$date')
That is NOT php! You forgot to use it in a query or something.
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');");
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()
This question already has answers here:
PHP, MySQL error: Column count doesn't match value count at row 1
(3 answers)
Closed 9 years ago.
I get this Exception:
Error 1136 : Column count doesn't match value count at row 1
Structure of the table :
create table gb_entries (
id int(4) not null auto_increment,
username varchar(40) not null,
name varchar(40),
gender varchar(40),
dob int(40),
email varchar(40),
primary key (id)
);
With this PHP code:
// Add a new entry to the database
function addEntry($username, $name, $gender, $dob, $email) {
$connection = mysql_open();
$insert = "insert into gb_entries " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
$result = # mysql_query ($insert, $connection)
or showerror();
mysql_close($connection)
or showerror();
}
// Return an array of database entries that contain $name anad $email
function getEntries($username,$name,$gender,$dob,$email) {
// Sanitise user input to prevent SQL injection attacks
$username = mysql_escape_string($username);
$name = mysql_escape_string($name);
$gender = mysql_escape_string($gender);
$dob = mysql_escape_string($dob);
$email = mysql_escape_string($email);
// Open connection and select database
$connection = mysql_open();
// Construct query
$query =
"select username, name, gender, dob, email from gb_entries where 0=0 ";
if (! empty($username)) {
$query .= "AND username LIKE '%$username%' ";
}
if (! empty($name)) {
$query .= "AND name LIKE '%$name%' ";
}
if (! empty($gender)) {
$query .= "AND gender LIKE '%$gender%' ";
}
if (! empty($dob)) {
$query .= "AND dob LIKE '%$dob%' ";
}
if (! empty($email)) {
$query .= "AND email LIKE '%$email%' ";
}
$query .= "ORDER BY id";
// echo $query;
// Execute query
$result = # mysql_query($query, $connection)
or showerror();
// Transform the result set to an array (for Smarty)
$entries = array();
while ($row = mysql_fetch_array($result)) {
$entries[] = $row;
}
mysql_close($connection)
or showerror();
return $entries;
}
What does the Exception mean?
As it says, the column count doesn't match the value count. You're providing five values on a six column table. Since you're not providing a value for id, as it's auto increment, it errors out - you need to specify the specific columns you're inserting into:
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')"
Also, I really hate that WHERE 0=0 line. I know why you're doing it that way, but I personally find it cleaner to do something like this (warning: air code!):
$query = "select username, name, gender, dob, email from gb_entries ";
$where = array();
if (! empty($username)) {
$where[] = "username LIKE '%$username%'"; // add each condition to an array
// repeat for other conditions
// create WHERE clause by combining where clauses,
// adding ' AND ' between conditions,
// and append this to the query if there are any conditions
if (count($where) > 0) {
$query .= "WHERE " . implode($where, " AND ");
}
This is personal preference, as the query optimizer would surely strip out the 0=0 on it's own and so it wouldn't have a performance impact, but I just like my SQL to have as few hacks as possible.
If the error is occurring when trying to insert a row to your table, try specifying the list of fields, in the insert query -- this way, the number of data in the values clause will match the number of expected columns.
Else, MySQL expects six columns : it expects the id column -- for which you didn't specify a value.
Basically, instead of this :
$insert = "insert into gb_entries " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
Use something like that :
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
I had a similar problem. The column count was correct. the problem was that i was trying to save a String (the value had quotes around it) in an INT field. So your problem is probably coming from the single quotes you have around the '$dob'. I know, the mysql error generated doesn't make sense..
funny thing, I had the same problem again.. and found my own answer here (quite embarrassingly)
It's an UNEXPECTED Data problem (sounds like better error msg to me). I really think, that error message should be looked at again
Does modifying this line help?
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
Is this possible if I want to insert some data into two tables simultaneously?
But at table2 I'm just insert selected item, not like table1 which insert all data.
This the separate query:
$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";
$sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";
Can I insert COUNT(model) at table2?
I have found some script, could I use this?
$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";
$result = mysql_query($sql,$conn);
if(isset($model))
{
$model = mysql_insert_id($conn);
$sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";
$result = mysql_query($sql,$conn);
}
mysql_free_result($result);
The simple answer is no - there is no way to insert data into two tables in one command. Pretty sure your second chuck of script is not what you are looking for.
Generally problems like this are solved by ONE of these methods depending on your exact need:
Creating a view to represent the second table
Creating a trigger to do the insert into table2
Using transactions to ensure that either both inserts are successful or both are rolled back.
Create a stored procedure that does both inserts.
Hope this helps
//if you want to insert the same as first table
$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
$result = #mysql_query($qry);
$qry2 = "INSERT INTO table2 (one,two, three) VVALUES('$one','$two','$three')";
$result = #mysql_query($qry2);
//or if you want to insert certain parts of table one
$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
$result = #mysql_query($qry);
$qry2 = "INSERT INTO table2 (two) VALUES('$two')";
$result = #mysql_query($qry2);
//i know it looks too good to be right, but it works and you can keep adding query's just change the
"$qry"-number and number in #mysql_query($qry"")
its cant be done in one statment,
if the tables is create by innodb engine , you can use transaction to sure that the data insert to 2 tables
<?php
if(isset($_POST['register'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$website = $_POST['website'];
if($username == NULL OR $password == NULL OR $email == NULL OR $website == NULL) {
$final_report2.= "ALERT - Please complete all fields!";
} else {
$create_chat_user = mysql_query("INSERT INTO `chat_members` (`id` , `name` , `pass`) VALUES('' , '$username' , '$password')");
$create_member = mysql_query("INSERT INTO `members` (`id`,`username`, `password`, `email`, `website`) VALUES ('','$username','$password','$email','$website')");
$final_report2.="<meta http-equiv='Refresh' content='0; URL=login.php'>";
}
}
?>
you can use something like this. it works.
In general, here's how you post data from one form into two tables:
<?php
$dbhost="server_name";
$dbuser="database_user_name";
$dbpass="database_password";
$dbname="database_name";
$con=mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to the database:' . mysql_error());
$mysql_select_db($dbname, $con);
$sql="INSERT INTO table1 (table1id, columnA, columnB)
VALUES (' ', '$_POST[columnA value]','$_POST[columnB value]')";
mysql_query($sql);
$lastid=mysql_insert_id();
$sql2=INSERT INTO table2 (table1id, table2id, columnA, columnB)
VALUES ($lastid, ' ', '$_POST[columnA value]','$_POST[columnB value]')";
//tableid1 & tableid2 are auto-incrementing primary keys
mysql_query($sql2);
mysql_close($con);
?>
//this example shows how to insert data from a form into multiples tables, I have not shown any security measures