Passing space in parameters to php file - php

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.

Related

Column count doesn't match value count at row 1 - PHP, MySql

I am inserting some data through PHP in MySql database, but unfortunately i am getting this error:
Error: Column count doesn't match value count at row 1
From the following code:
<?php
if($_POST)
{
include_once('dbconn.php');
$profile_created_by = $_POST['profile_created_by'];
$name = $_POST['name'];
$gender = $_POST['gender'];
$dd = $_POST['dd'];
$mm = $_POST['mm'];
$yyyy = $_POST['yyyy'];
$dob = $dd.'-'.$mm.'-'.$yyyy;
$marital_status = $_POST['marital_status'];
$religion = $_POST['religion'];
$mother_tongue = $_POST['mother_tongue'];
$country = $_POST['country'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$password = $_POST['password'];
$sql="INSERT INTO user VALUES ('$profile_created_by', '$name', '$gender', '$dob', '$marital_status', '$religion', '$mother_tongue', '$country', '$mobile', '$email', '$password')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
echo "Entered data successfully";
mysql_close($conn);
}
?>
Can anybody help me out with this error?
If you have more columns in user table which are not mentioned here (e.g ID), You have to specify which data is for which column.
$sql="INSERT INTO user (profile_created_by,name,gender,dob,marital_status,religion,mother_tongue,country,mobile,email,password) VALUES ('$profile_created_by', '$name', '$gender', '$dob', '$marital_status', '$religion', '$mother_tongue', '$country', '$mobile', '$email', '$password')";
You are getting this error bcoz number of columns in the table user doesn't match with number of values supplied. So try using this type of format:
INSERT INTO user(columnNames,...)
VALUES(respective_values,....);

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

php codes stops running halfway through

I have created a php function that allows users to save their address on the database. My issue is that part of the code doesn't run at all. The code stops running at $result2= "SELECT * FROM Addressv4 WHERE Userid = '".$id."'";
It then starts working when it reaches this line of code $insert_query = "INSERT INTO Addressv4 (Userid, Housenumber, Street, Town, Postcode, DefaultAddress)
values ('$id', '$Number', '$Street', '$Town','$Postcode', '1')";
I haven't received any syntax errors when running the code either.
Any help would be grateful.
<?php
include 'dbconnect.php';
$connection = mysqli_connect($db_host, $db_username, $db_password, $db_database);
// Check connection
if (mysqli_connect_errno($connection)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Getting data from HTML Form
$Number = $_POST['streetnumber'];
$Street = $_POST['street'];
$Town = $_POST['town'];
$Postcode = $_POST['postcode'];
$Username = $_POST['Username'];
$sql = mysqli_query($connection, "SELECT * FROM Userv2 WHERE Username = '".$Username."'");
if ($sql){
while($row = mysqli_fetch_array($sql)){
$id = $row['Id'];
}
}
$result2= "SELECT * FROM Addressv4 WHERE Userid = '".$id."'";
$sql1 = mysqli_query($connection, $result2);
$count = count($sql1);
if($count >=1){
echo 'Sorry you can only have 1 default address';
}
$insert_query = "INSERT INTO Addressv4 (Userid, Housenumber, Street, Town, Postcode, DefaultAddress)
values ('$id', '$Number', '$Street', '$Town','$Postcode', '1')";
$result = mysqli_query($connection, $insert_query);
header("Location: http://sots.brookes.ac.uk/~10031187/viewaddress.php");
mysqli_close($connection);
?>
maybe it's better to use
SELECT COUNT(Userid) AS countId FROM..
if ($row['countId'] > 1) {
that way the query will always return something, now there is a chance your query can return false..
what is the output of var_dump($sql1); ?
$sql1 is a resulset. You cannot count the number of lines like this.
Try :
$sql1_count = mysqli_num_rows($sql1)

How to call a function/method in php to insert function return value to mysql

<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
function random_string($length) {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
if($email)
{
$connect = mysql_connect(" HOST ", " USERNAME ", " PASSWORD") or die("Couldn't Connect");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database");
$query = "INSERT INTO customers (fname, lname, email, alphanum) VALUES ('$fname', '$lname', '$email', 'random_string(10)')";
$result = mysql_query($query) or die("Some kind of error occured.");
echo ("Welcome " + $username + ", you are now in my database!");
}
else die("You did not fill out the fields correctly, please try again.");
?>
I need help with the line in the middle that starts with $query = "INSER ... 'random_string(10)')";
I need a random alphanumeric string to be inserted into the table called "customers" but instead of calling the function "random_string()" it inserts "random_string(10)" into my table which gives me this for my table with 6 fields:
5 John Smith Jogsz#CiniCraft.com random_string(10) 0
How do I fix this?
$query = "INSERT INTO customers (fname, lname, email, alphanum) VALUES ('$fname', '$lname', '$email', '" . random_string(10) . "')";
This should work!
I think that even though double quotes will parse variables, they wont parse functions.
concatenate the function and your string,
$query = "INSERT INTO customers (fname, lname, email, alphanum) VALUES ('$fname', '$lname', '$email', '" . random_string(10) ."')";
As a sidenote, the query is vulnerable with SQL Injection if the values of the variable came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
make two statements of it. In the first statement you call your function and assign the value to a variable and then in your INSERT... statement you use the variable

PHP, Error 1136 : Column count doesn't match value count at row 1 [duplicate]

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

Categories