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.
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;
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 want to prevent if the user enters same email twice, which will create duplicate entry. Please help me to solve this small problem, I have searched stackoverflow for this problem but everyone has their own database with own method.
Thank you
<form action="create_subscriber.php" method="post">
<input placeholder="Name" name="inputName" type="name" required/>
<input name="inputEmail" placeholder="example#email.com" name="Submit" type="email" required/>
<input name="Submit" type="submit" value="Subscribe"/>
</form>
create_subscriber.php below
<?php
//include 'connection.php'
$dbhost = "localhost";
$dbuser = "sampleuser";
$dbpass = "samplepass";
$dbname = "sampledb";
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
$name = $_POST['inputName'];
$email = $_POST['inputEmail'];
if(!$_POST['Submit']){
echo "Please enter a name & email";
//header('Location: index.php');
}else{
mysql_query("INSERT INTO subscriptions
(`ID`,`Name`, `Email`) VALUES(NULL,'$name', '$email' ) ")
or die(mysql_error());
echo "User has been added";
header('Location: success.php');
}
?>
Since you are not doing any validation, you can use the Email as a unique field and do an REPLACE query. http://dev.mysql.com/doc/refman/5.0/en/replace.html
I would strongly advise you to write validation in the form of a query check against the database prior to attempting to do a secondary insert. It's even made easy by persistent connections being available so you don't have the overhead of few ticks it takes to do that validation query.
mysql_query("INSERT INTO subscriptions
(`ID`,`Name`, `Email`) VALUES (NULL,'$name', '$email' )
WHERE NOT EXISTS (
SELECT email FROM subscriptions WHERE email='$email'
)")
Simply execute a preliminary query to check for email uniqueness
SELECT * FROM subscriptions WHERE `email` = ?
(I wrote the query in the form of a prepared statement
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
You should use prepared statement to inject values into queries).
If you get any row then the email is not unique so redirect to the original form page, possibly displaying an error message.
If you don't get any record then you may proceed with the insert and then render a "mail registration succeeded" page.
Btw: you can't echo something and then set a header. As you start sending output header can't be set/changed.
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 **/