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);
Related
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 using MAMP as my localhost environment and i am trying to pass values from html form to database through php.when i submit my form i face following error:
INSERT INTO social (facebook, google, twitter) VALUES ('sdf','sdf','sdf')
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'firsttest.social' doesn't exist
html:
<html>
<form name='form' method='post' action="m.php">
Fb : <input type="text" name="fb" >
google : <input type="text" name="google" >
twitter : <input type="text" name="twitter" >
<input type="submit" name="save_to_db" value="Submit">
</form>
</html>
PHP:
<?php
if(isset($_POST['save_to_db'])){
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "firsttest";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to create table
$sql = "CREATE TABLE social (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
facebook VARCHAR(30) NOT NULL,
google VARCHAR(30) NOT NULL,
twitter VARCHAR(50),
reg_date TIMESTAMP
)";
$sql = "INSERT INTO social (facebook, google, twitter)
VALUES ('".$_POST["fb"]."','".$_POST["google"]."','".$_POST["twitter"]."')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
You're not executing the CREATE TABLE query, but instead, you overwrite it with the INSERT query instantly.
Try using a debug tool like xdebug or something, so you could walk step by step through your code, that will help you find bugs in your code easily.
Also, creating a database table each time you want to save data to the database is not wise. Try setting up the whole database before starting to work with it.
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
Ok, so after installing wamp server, I have gone to the phpMyAdmin page and created a database called db2. After that, I have created a table inside of that database called cnt2. It has 5 columns, ID, Name, Mark1, Mark2 and Mark3. So, I have one html php file that allows you to view the information in the database, and this works just fine. However, my second html php document is supposed to allow you to add new information into the database. I have followed 2 different tutorials on this as I have never done php or any html script before, but it just isn't working. I'll post both codes/scripts below.
http://gyazo.com/467f8e3a066992c0753eec2d5912bdba << Database page
http://gyazo.com/82a1c2107fb75c4c2941583449b4504a << Input page with error
Database code
<html>
<body>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("db2",$dbhandle)
or die("Could not selected db2");
echo "Coneted to db2<br>", "<br>";
$result = mysql_query("SELECT ID, Name, Mark1, Mark2, Mark3 FROM cnt2");
while($row = mysql_fetch_array($result)){
echo "<b>Name: </b>".$row{'Name'}." <b>ID: </b>".$row{'ID'}." <b>First Mark: </b>".$row{'Mark1'}." <b>Second Mark: </b>".$row{'Mark2'}." <b>Third Mark: </b>".$row{'Mark3'}."<br>";
}
mysql_close($dbhandle);
?>
</body>
</html>
Input code
<HTML>
<?php
if($submit){
$db = mysql_connect("localhost", "root","");
mysql_select_db("db",$db);
$sql = "INSERT INTO cnt2 (ID, Name, Mark1, Mark2, Mark3) VALUES ('$id','$name','$markone','$marktwo','$markthree','$result = mysql_query($sql))";
echo "Thanks! Data received and entered.\n";
}
else{
?>
<form method="post" action="datain.php">
id:<input type="Int" name="ID"><br>
name:<input type="Text" name="Name"><br>
markone:<input type="Int" name="Mark1"><br>
marktwo:<input type="Int" name="Mark2"><br>
markthree:<input type="Int" name="Mark3"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?
}
?>
</HTML>
Thanks for any help :)
You're not actually requesting your post headers to pull your vars in
<html>
<?php
if($submit){
//need to request post vars here
$id=mysql_real_escape_string($_POST['ID']);
$name=mysql_real_escape_string($_POST['Name']);
$markone=mysql_real_escape_string($_POST['Mark1']);
$marktwo=mysql_real_escape_string($_POST['Mark2']);
$markthree=mysql_real_escape_string($_POST['Mark3']);
$db = mysql_connect("localhost", "root","");
mysql_select_db("db",$db);
$sql = "INSERT INTO cnt2 (ID, Name, Mark1, Mark2, Mark3) VALUES ('$id','$name','$markone','$marktwo','$markthree')";
mysql_query($sql) or die(mysql_error()."<br />".$sql);
echo "Thanks! Data received and entered.\n";
}
else{
?>
<form method="post" action="datain.php">
id:<input type="Int" name="ID"><br>
name:<input type="Text" name="Name"><br>
markone:<input type="Int" name="Mark1"><br>
marktwo:<input type="Int" name="Mark2"><br>
markthree:<input type="Int" name="Mark3"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?php // stop using short tags i've swapped it to a proper open
}
?>
</html>
Also if you're only just using don't use mysql_ functions look into mysqli or pdo especially prepared statements instead of directly injecting variables into queries as we have done above
The problem may be in this line:
$sql = "INSERT INTO cnt2 (ID, Name, Mark1, Mark2, Mark3) VALUES ('$id','$name','$markone','$marktwo','$markthree','$result = mysql_query($sql))";
As You may notice (at the end), it should probably be like this:
$sql = "INSERT INTO cnt2 (ID, Name, Mark1, Mark2, Mark3) VALUES ('$id','$name','$markone','$marktwo','$markthree')";
$result = mysql_query($sql);
As all other people mentioned, do not use mysql_* functions as they are DEPRECATED, instead of this stick with PDO or at least mysqli.
Also, the part
if($submit){
may never be satisfied unless You set the $submit variable somewhere before... Shouldn't it rather be
if (isset($_POST['submit'])) {
???
And, please, read about code formatting - Your code looks like crap... Best choice is to stick with PSR-0, PSR-1 and PSR-3 - use Google to read something about it...
create database android_api /** Creating Database **/
use android_api /** Selecting Database **/
create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
); /** Creating Users Table **/
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.