Failed to insert into MYSQL table - php

Right, im just doing a little bit of testing before building my project and i keep getting errors. I'm using WAMP and phpmyadmin for the database.
I have managed to connect to the database successfully, but cannot seem to insert data into the table.
Ultimately i want to insert data the user uploads from a form but I'm using static figures for now to get the INSERT working correctly.
So when the user clicks submit, i want this to run;
PHP/MYSQL:
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "#########");//I have hashed out the password here
define("DB_NAME", "uploads");
// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
$query = "INSERT INTO ";
$query .= "customers ";
$query .= "(`reference`, `doc1`, `doc2`, `doc3`) ";
$query .= "VALUES ('123456', 'newimage1.jpg', 'newimage2.jpg', 'newimage3.jpg')";
$result = mysqli_query($connection, $query);
if ($result) {
echo "created insert";
} else {
// Failure
echo "failed to insert";
}
Okay so the database connection works as it throws no errors, however i just get "failed to insert".
Any ideas guys? if you need more info just post a comment
EDIT:
echo the $query i get:
INSERT INTO customers(reference, doc1, doc2, doc3) VALUES ('123456', 'newimage1.jpg', 'newimage2.jpg', 'newimage3.jpg')failed to insert
and its the same if i remove the space on customers
WORKING:
The fields where varchar 11, and the text was too long to be inserted. Very stupid mistake haha, relatively new to using MYSQL with php. But thanks for the help!

As per your question there is a mistake in you table structure change the varchar size (increase more than 11 )to insert data int table for column doc1 doc2 doc3

Related

How can I get mysql to print rows from a database table

I am trying to learn php from W3schools which includes a mysql section.So far I have completed every other part of the tutorial on w3school except the part that prints content from a database table. For some very weird reason , nothing displays when I run my code. Please how can I get this working and could my problem come from the fact that I am using MariaDB with Xampp instead of Mysql although they said it was practically the same syntax.
Here is the code
<?php
$servername = "localhost";
$username = "uhexos";
$password = "strongpassword";
$database = "fruitdb";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE fruitDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
// Create connection
$conn = mysqli_connect($servername, $username, $password,$database);
// sql to create table
$complexquery = "CREATE TABLE MyFruits (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
FruitType VARCHAR(30) NOT NULL,
FruitTaste VARCHAR(30) NOT NULL,
FruitQuantity INT NOT NULL,
DatePurchased TIMESTAMP
)";
if ($conn->query($complexquery) === TRUE) {
echo "Table Fruits created successfully<br> ";
} else {
echo "Error creating table: " . $conn->error;
}
$entry = "INSERT INTO myfruits (fruittype,fruittaste,fruitquantity) VALUES ('orange','sweet','50'),('lemon','sour','10'),('banana','sweet','15')";
if ($conn->query($entry) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $conn->error;
}
$sql = 'SELECT id, fruitname, fruittaste FROM myfruits';
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['id']} <br> ".
"EMP NAME : {$row['fruitname']} <br> ".
"EMP SALARY : {$row['fruittaste']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
this is the output I get from all my echos.
Error creating database: Can't create database 'fruitdb'; database existsError creating table: Table 'myfruits' already existsNew records created successfully
or
Database created successfullyTable Fruits created successfully
New records created successfully
Based on the error message, you managed to create the database and tables once and now each time you run the code it fails because you can't reuse the names.
You definitely don't want to have code trying to erase & start fresh on your database every time. In fact, most often I find that you don't even create the database inside your regular code but use phpMyAdmin or some other admin page to do that. But creating tables inside code is normal enough. Two options:
1 - Create the table only if it does not already exist. This is extremely safe. However, if you want to start a table over again with a new structure, or start with it always empty, that won't work. To do that, just change CREATE TABLE to CREATE TABLE IF NOT EXISTS
2 - Delete the table before creating it. Before each CREATE TABLE command, add a command like DELETE TABLE IF EXISTS MyFruits
Remember database name is Case-insensitive, so it doesn't matter whether you create a DB name "fruitdb" or "fruitDb" both are same.That is the reason you are getting error. Also you don't have to create a new database when you execute any file. If you have already created the database than you only have make the connection with it.
Let's debug your code line by line.
Line 8 -
// Create connection
$conn = new mysqli($servername, $username, $password);
Here you are creating the connection with your database because you have already created that database. If you check your phpmyadmin, you'll find a database named "fruitdb"
Line 10 -
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Here your checking whether the you are able to connect with your database. If not it will throw the error and your script will stop. Right now your code successfully runs till this point.
Line 15 -
// Create database
$sql = "CREATE DATABASE fruitDB";
Here you are again creating a database with same name and your code stops working as you already have it.
The error was from this line
$sql = 'SELECT id, fruitname, fruittaste FROM myfruits';
I accidentally put fruitname instead of fruittype and that is what caused it to fail. So for anyone else with thi problem my advice is to check your variable names if you are 100% sure of your syntax. Thanks for all the help.

how to insert data in mysql database using mysqli with data checking no same "id" in same "date"

guy's i need your help. im trying to make an insert form with php with this condition.
"id cant be same in same date"
my database name is : "ssl",
table name is : "try"
with table col: "id", "date", "name", "city"
im have try a lot to make this but still get some eror. but when i delete the php script for checking it can running well..
please help me. im really apreciated when you give me an example of that.
sorry for my english and sorry im still newbie and need study more for something like this
this my script for insert
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "silo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$sql="Insert into termocouple
Select * from temp1";
if(mysqli_query($link, $sql)){
echo "Data inserted successfully.";
} else{
echo "Data inserted Failed " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
can i just use something like this?
i get from Copy rows from one table to another, ignoring duplicates
<?php
$sql="INSERT INTO termocouple
SELECT no,tanggal,silo,...
FROM temp1
WHERE NOT EXISTS(SELECT *
FROM destTable
WHERE (temp1.no=termocuple.no and
temp1.tanggal=termocouple.s_tanggal...etc.)
)";
?>

How to connect to a new database using PHP MySQL

So I've been trying to learn how to use MySQL with PHP, and I've managed to create a connection and create a database along with a table. What I don't know how to do is create the database along with the tables all in one go.
What I mean by this is easier shown in my code (Which will show unable to connect error message because the connect method is trying to connect to a database that does not exist.
<?php
$servername = isset($_POST["servername"]) ? $_POST["servername"] : '';
$username = $_POST["username"];
$password = $_POST["password"];
$dbname = $_POST["dbname"];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
So, all I am trying to achieve is Connect to MySQL, create the database, create a table for said database and close the connection all within one .php file.
On a side note, due to the user being able to define a database name ($dbname), how would I add this value into the MySQL code above? I heard somewhere that you're supposed to add the variable into quotes? So '$dbname'. Any help with that would be good too! Thanks in advance!
Okay, the reason for this question is because I am creating a setup-type page where the user will be able to connect to their own database, allowing them to give it a name and connect using their credentials. Obviously I am not very experienced within this field, I hope I have explained it better.
All the code you have looks fine to me. The only thing I think your missing is after you create a database you have to call
$conn->select_db("myDB");
Also if you want to have the database name be $dbname then
$sql = "CREATE DATABASE myDB";
should be
$sql = "CREATE DATABASE " . $dbname;
If I didn't cover your problem please give me more detail on your problem.
where you passing all of this variable ?
$servername = isset($_POST["servername"]) ? $_POST["servername"] : '';
$username = $_POST["username"];
$password = $_POST["password"];
$dbname = $_POST["dbname"];
just simply hardcode the servername, username, password and your dbname.

PHP Mysqli SELECT, INSERT and UPDATE from different databases

I am trying to select values from one DB. And insert and update the result into another. This is cronjob that needs to run everyday to replicate some data from one DB into another. I know I am missing steps / correct syntax, but I hope someone can help me out.
<?php
$con_1=mysqli_connect("host","user","pw","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$con_2=mysqli_connect("host","user","pw","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con_1,"SELECT id, name FROM table GROUP BY 1,2");
$mysqli->query($con_2, "INSERT INTO `table2`(`id`, `name`) VALUES ('".$result[1]."', ".$result[2].")
ON DUPLICATE KEY UPDATE name = ".$result[2]."");
}
mysqli_close($con_1);
mysqli_close($con_2);
?>
mysqli_query returns a query object, using $result[1] doesn't make sense, you need to fetch the rows in a loop:
while($row = $result->fetch_assoc()) {
// insert result in second database
}
For other access methods check the documentation.

PHP MySQL - Error: No Database selected

I am trying to read and write to a database. Here is the code I have so far:
$mysql = mysqli_connect("example.com", "johndoe", "abc123"); // replace with actual credidentials
$sql = "CREATE DATABASE IF NOT EXISTS dbname";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating database: " . mysqli_error($mysql);
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($mysql);
$mysql = mysqli_connect("example.com", "johndoe", "abc123", "dbname"); // replace with actual credidentials
$sql = "CREATE TABLE IF NOT EXISTS Users(ID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(ID), username CHAR(15), password CHAR(15), email CHAR(50))";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating table: " . mysqli_error($mysql);
}
$sql = "INSERT INTO Customers(username, password, email) VALUES(" . $username . ", " . $password . ", " . $email . ")";
if (!mysqli_query($mysql, $sql)) {
echo "Error: " . mysqli_error($mysql);
}
mysqli_close($mysql);
However, when I try to run it, it has an error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , )' at line 1
Could anybody tell me how to fix this?
Please check syntax of mysqli, it takes 4 parameters.You also have to provide database name.
$link = mysqli_connect("myhost","myuser","mypassw","my_db");
You're missing database in mysqli_connect() call
$link = mysqli_connect("hostname","username","password","database") or die("Error " . mysqli_error($link));
Obviously the answer is in your error. You didn't select any database. When using this function mysqli_connect specify the database you want to connect to.
Here is the syntax of the function: http://www.w3schools.com/Php/func_mysqli_connect.asp .
1) Create your database outside of your application
2) Specify mysqli_connect with the database you want to select.
You can also use another function called mysqli_select_db . You can find the sytanx here : http://www.w3schools.com/php/func_mysqli_select_db.asp .
As already stated in the comment, you will also have to replace : "example.com" with your ip address, if you are running locally replace it with 127.0.0.1:3306 , if you didn't change the port when you installed your mysql database / "johndoe" with your database account, you can change that to "root" / "abc123" with your root account password DEFAULT : "" .
Good luck !
First check mysqli_select_db if it returns false then create database.
try like this:
$mysql = mysqli_connect("example.com", "johndoe", "abc123") or die(mysqli_connect_error()); // replace with actual credidentials
if (!mysqli_select_db($mysql,'hardestgame_accounts')) {
$sql = "CREATE DATABASE IF NOT EXISTS hardestgame_accounts";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating database: " . mysqli_error($mysql);
}
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "CREATE TABLE IF NOT EXISTS Users(ID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(ID), username CHAR(15), password CHAR(15), email CHAR(50))";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating table: " . mysqli_error($mysql);
}
mysqli_close($mysql);
here is a good answer: Php mysql create database if not exists
Try using mysql_select_db in between the database connection and the table creation.
Also, mysql_ is deprecated, please use mysqli_ instead
Use ` backticks for MYSQL reserved words...
your table name is reserved word for MYSQL...
Change your table name.

Categories