trying to do and upload csv script and hitting an error that doesn't make sense. invalid token. It says my columns don't match my ?,?,?,?,?. 5 columns, 5 ? question marks, what did I miss?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<form enctype="multipart/form-data" method="POST">
<input name="userfile" type="file">
<input type="submit" value="Upload">
<input name="row_name" type="text">
</form>
<?php
$dsn = "mysql:host=$host;port=$port;dbname=$dbname"; //Data Source Name = Mysql
(isset($rowname = $_POST['row_name']));
$db = new PDO($dsn, $db_username, $db_password); //Connect to DB
$do = $db->prepare(
"CREATE TABLE IF NOT EXISTS $username.$rowname (
id INT AUTO_INCREMENT NOT NULL,
list_name varchar(100) NOT NULL,
fname char(60),
lname char(60),
list_email varchar(100),
PRIMARY KEY (id)
)
CHARACTER SET utf8 COLLATE utf8_general_ci
TRUNCATE TABLE $username.$rowname
INSERT INTO $username.$rowname VALUES(?,?,?,?,?)"
);
$csv_file = $_FILES['userfile']['tmp_name'];
if (($handle = fopen($csv_file, "r")) !== FALSE) {
while (($data = fgetcsv($handle)) !== FALSE) {
$do->execute($data);
var_dump($data);}
fclose($handle);}
exit( "Complete!" );
?>
</body>
</html>
error
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in /home/wemail1/www/pages/campaign-build.inc.php on line 58
Sample data:
fname, lname, email
joe, schmoe, bogus#bogus.com
mary, lamb, hoe#us.com
Your $data hasn't got 5 params. And this is what say the error message too. You have 3 value, and the code want 5 value. You need something like this:
$insert = array(NULL, $data[0]." ".$data[1], $data[0],$data[1],$data[2]);
$do->execute($insert);
Instead of:
$do->execute($data);
So, If you have 5 ? in your prepare, you need an array which have 5 values, or you got that error.
Related
I am trying to learn inserting image into phpmyadmin my db structer:
id int(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
mime VARCHAR(255),
data BLOB
my code is:
<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
$dbh = new PDO("mysql:host=localhost;dbname=mydata", "root", "123456");
if(isset($_POST['btn'])){
$name = $_FILES['myfile']['name'];
$type = $_FILES['myfile']['type'];
$data = file_get_contents($_FILES['myfile']['tmp_name']);
$stmt = $dbh->prepare("INSERT INTO myblob VALUES('',?,?,?)");
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$type);
$stmt->bindParam(3,$data);
$stmt->execute();
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="myfile" />
<button name="btn">Upload</button>
</form>
my error on submit:
Uncaught PDOException: SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '' for column `mydata`.`myblob`.`id` at row 1
Any ideas what is wrong there when trying to upload a png file?
The problem is that you're sending an empty string at the 'id' value:
$stmt = $dbh->prepare("INSERT INTO myblob VALUES('',?,?,?)");
The correct would be to tell the columns with the values to add not sending anything for the 'id' column since it's is an auto increment
$stmt = $dbh->prepare(INSERT INTO myBlob(name, type, data) VALUES(:name, :type, :data)
$stmt->bindParam('name',$name);
$stmt->bindParam('type',$type);
$stmt->bindParam('data',$data);
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
How can I get useful error messages in PHP?
(41 answers)
Closed 1 year ago.
Update query not taking integer variable ($user):-
$user = $_POST["user"];
$user = (int)$user;
$sql = "UPDATE users_meta
SET
`meta_value` = '$plan_end'
WHERE
`user_id` = $user AND
`meta_name` = 'plan_end'";
$conn->query($sql);
user_id column in mysql database is set to int datatype.
When I simply put a number instead of the variable, it works:-
WHERE
`user_id` = 37 AND ...
I also tried without converting the number from string to int, and its not working. I have a feeling that it has something to do with quotes, so I played around with it based on suggestions online, but none worked.
As per based on my knowledge if database field is of Int type then it cannot accept character/string values even you are converting them into type of integer. You have to modify the database field to varchar or you have to pass only numeric values to the database field. Hope this suggestion may solve your problem.
Hi I have tested your query on my local it works fine so I don't think there is any thing wrong with you query.
<?php
$mysqli = new mysqli("localhost","root","","test_table");
// Check connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
if(#$_POST["user"])
{
$user = $_POST["user"];
$tasone = $_POST["tasone"];
$user = (int)$user;
$sql = "UPDATE test_table SET `TAS_ONE` = '$tasone' WHERE `user_id` = $user and `TAS_TWO`='dsadsa'";
$mysqli->query($sql);
}
?>
<form action="" method="post">
<input type="text" id="user" name="user" value=""><br>
<input type="text" id="tasone" name="tasone" value=""><br>
<input type="submit" value="Submit">
</form>
CREATE TABLE `test_table` (
`USER_ID` int(9) NOT NULL,
`TAS_ONE` varchar(200) NOT NULL,
`TAS_TWO` varchar(200) NOT NULL,
`TAS_THREE` varchar(200) NOT NULL,
`TAS_FOUR` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I was trying to make a sql database and i have faced some issues regarding INSERT INTO TABLE.
I have noticed that sql is not allowing me to insert data in a table if the name of Database is u759286173 i am able to insert data into table using any other name but this particular (u759286173) database name is not allowing me to insert data in table
I have tried various database names which works
759286173
759286173_quebec
759286173_grvnaz
u_grvnaz
Can someone please explain me that why data is not inserting in table when i allow the database name to be u759286173
My Database name : u759286173
My Table name : mydb
Please reply if u face the same issue or have a solution.
Any help is appreciated.
My Code
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "u759286173";
$dbHost = " localhost";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
other code
<?php
session_start();
include 'dbh.inc.php';
if (isset($_POST) & !empty($_POST)) {
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$message = $_POST['message'];
$sql = "INSERT INTO mydb (first, last, email, message)
VALUES ('$first', '$last', '$email', '$message');";
mysqli_query($conn, $sql);
header("location: ../signup.php?send=success");
} else {
header('location: ../failed.php');
exit();
}
?>
Form Code
<!DOCTYPE>
<html>
<body>
<form class="registerform" action="includes/contact.inc.php" method="POST">
<input type="text" placeholder="first" name="first" required/>
<input type="text" placeholder="last" name="last" required/>
<input type="email" placeholder="E-mail ID" name="email"/>
<input type="text" placeholder="message" name="message" required/>
<button name="submit" type="submit">Create</button>
</form>
</body>
</html>
=Database u759286173
CREATE TABLE IF NOT EXISTS `mydb` (
`id` int(11) NOT NULL,
`first` varchar(32) NOT NULL,
`last` varchar(32) NOT NULL,
`email` varchar(50) NOT NULL,
`message` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The INSERT statement does not provide a value for the id column.
The id column is defined to be NOT NULL and does not have AUTO_INCREMENT property. (And we assume there isn't a BEFORE INSERT trigger that assigns a value to NEW.id
Given the table definition, we expect that when the INSERT statement is executed, MySQL will issue
Error Code: 1364
Field 'id' doesn't have a default value
(This could be a Warning rather than Error with some settings of sql_mode.)
Most important is that we check for MySQL error condition; this will provide the information we need in order to determine what the problem is.
At the top of the script, enable PHP and mysqli error reporting:
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
That will get use the information we need when a MySQL error occurs.
I am trying to enter the data that I get from the two variables stuname and book in the table's username and book columns !! I only want to enter data into those two columns since the id column is auto increment and the date is auto updated with time stamp!!! Each time I run my code I enter my data into the two text fields and when I press submit I get this message!!
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\assignment.php on line 35
Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\assignment.php on line 36
Here is my Code:
<?php
$servername = "localhost";
$Username = "root";
$Password = "admin";
$Dbname = "nfc";
$conn = mysqli_connect($servername, $Username, $Password, $Dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "Connected successfully";
if(isset($_POST["stuname"])&&($_POST["book"]))
{
$stuname = $_POST["stuname"];
$book =$_POST["bookname"];
$sql = "INSERT INTO library (id, username, book, date)
VALUES ('', '$stuname', '$book','')";
mysqli_select_db($conn, 'nfc') or die(mysqli_error($con));
$retval = mysqli_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
else
{
echo "Success";
}
echo " to stuname ". $stuname;
echo " to book ". $book;
}
?>
<form id="form1" name="form1" method="post" action="#">
<p>
<label for="1">student name</label>
<input type="text" name="stuname" id="1" />
</p>
<p>
<label for="12">book name</label>
<input type="text" name="bookname" id="12" />
</p>
<input name="submit" type="submit" value="Submit" />
</form>
In the mysqli_query you should put the conn first and then the query itself
$retval = mysqli_query( $conn, $sql );
The first problem was solved by #Ghost in the comments.
Now on to the rest of the problems:
1. Your database design is faulty
This should have failed immediately because you are inserting an empty value for id. id should be a primary key and therefore should be unique. An auto-increment doesn't work if you insert an empty value.
2. Your insert statement is faulty
You should exclude an auto-increment column in the INSERT statement and should not use an empty value for date. If date is a timestamp, you should either use NULL if the time is supposed to be empty or use NOW() to use the current timestamp.
3. You shouldn't be using insert on this page according to your comments.
You should be using UPDATE or REPLACE instead of INSERT if you are trying to update the existing row but you should be using the primary key to signify which row you are replacing. Right now, it looks like you don't have a primary key, so refer to my 1st point.
4. Security concerns: Your query is subject to SQL injections.
You use user input ($_POST) directly in a query. Any malicious user can take advantage of this and extract, delete, or manipulate data in your database. You should be using prepared statements, or at the very least escape functions.
I have this code:
<form action="#" method="post">
<input type="text" name="famname"/>
<input type="submit" name="submit"/>
</form>
<?php
if(isset($_POST['submit'])){
if(!isset($_POST['famname'])){
echo "Please set Family Name.";
die();
}
$mysqli = new mysqli('localhost', 'root', 'marais19', 'famlink');
if($mysqli->connect_errno) {
echo "Connection Failed (".$mysqli->connect_errno.") : ".$mysqli->connect_error;
die();
}
$e = 'yes';
$stmt = $mysqli->prepare("INSERT INTO families(famname) VALUES (?)");
$stmt->bind_param('d', $e);
$stmt->execute();
}
?>
But if I type Smith into the input box it only puts 0 into the database. The SQL code is as followed:
CREATE TABLE IF NOT EXISTS `families` (
`famname` varchar(30) CHARACTER SET utf8 NOT NULL DEFAULT 'NOFAM',
KEY `famname` (`famname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
And:
INSERT INTO `families` (`famname`) VALUES
('0');
How can I make it to put Smith into the database and not 0
You are casting it to a number (actually a double) when you bind it to the query. You need to use s instead of d:
$stmt->bind_param('d', $e);
should be
$stmt->bind_param('s', $e);
See the manual on types:
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets