MySQL returned an empty result set - php

i dont understand why mysql table return empty result set, the code seems okay.
the response from mysql: MySQL returned an empty result set (i.e. zero rows). (Query took 0.0010 sec)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "myexcel";
// Create connection
$connection = mysqli_connect($servername, $username, $password, $database);
if (isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen( $file, "r");
while(($fileop = fgetcsv($handle, 3000, ",")) !== false)
{
$id = $fileop[0];
$name = $fileop[1];
$sql = "INSERT INTO csv (id, name) VALUES ('$id', '$name')";
}
if ($sql)
{
echo "OK";
}
}
?>
<html>
<body>
<input type="file" name="file" id="file">
<input type="submit" value="Upload" name="submit">
</body>
</html>

You forgot to query:
$sql = mysqli_query($connection, "INSERT INTO csv (id, name) VALUES ('$id', '$name')");

Add mysqli_query and put your if condition inside while loop.... And i could not see any form tag in your code ??? I have added here with post method
?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "myexcel";
// Create connection
$connection = mysqli_connect($servername, $username, $password, $database);
if (isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen( $file, "r");
while(($fileop = fgetcsv($handle, 3000, ",")) !== false)
{
$id = $fileop[0];
$name = $fileop[1];
$sql = mysqli_query($connection, "INSERT INTO csv (id, name) VALUES ('$id', '$name')");
if ($sql)
{
echo "Ok. Inserted <br>";
}
}
}
?>
<html>
<body>
<form method="POST"> // add this
<input type="file" name="file" id="file">
<input type="submit" value="Upload" name="submit">
</form>
</body>
</html>

Related

Upload multiple images to database

the 5 pictures i want to upload are used to display the product with a gallery that you click on each image to see individually, i'm new to this so any feedback on how to improve my code is appreciated :)
config.php:
<?php
session_start();
// connect to database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ecommerce_site";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
manage.php:
<form method="POST" action="manage.php" enctype="multipart/form-data">
<input type="file" name="image[]" multiple>
<button type="submit" name="upload_product">Post</button>
</form>
admin-functions.php:
<?php
if (isset($_POST['upload_product'])){
$filecount = count($_FILES['image']['name']);
for($i = 0 ; $i < $filecount ; $i++){
$filename = $_FILES['image']['name'][$i];
$sql = "INSERT INTO products (picture, picture_2, picture_3, picture_4, picture_5) VALUES ('$filename', '$filename', '$filename', '$filename', '$filename',)";
if($conn->query($sql) === TRUE){
echo"success";
}
else{
echo "error";
}
move_uploaded_file($_FILES['image']['tmp_name'][$i], '../static/images/'.$filename);
}
}
$result = mysqli_query($conn, "SELECT * FROM products");
?>
database

can't complete on fgetcsv in mysql

<?php
header('Content-Type: text/html; charset=utf-8');
$servername = "localhost";
$username = "root";
$password = "abc";
$dbname = "project";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "TRUNCATE TABLE datapack";
mysqli_query($conn,$sql);
if(isset($_POST['submit']))
{
$fname = $_FILES['sel_file']['name'];
echo 'upload file name: '.$fname.' ';
$chk_ext = explode(".",$fname);
if(strtolower(end($chk_ext)) == "csv")
{
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
$head = fgetcsv($handle);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sql= "INSERT into datapack(id,nickname,time,msg) values('$data[0]','$data[1]','$data[2]','$data[3]')";
mysqli_query($conn,$sql);
echo "Error: ". $conn->error;
}
echo "Success!";
}
else
{
echo "Invalid File";
}
}
?>
<h1>Import CSV file</h1>
<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post' enctype="multipart/form-data">
Import File : <input type='file' name='sel_file' size='20'>
<input type='submit' name='submit' value='submit'>
</form>
After I run the file, i find some problems:
The file cannot completely import to mysql (for example, only 600 lines can imports when there is 1000 lines in csv), and everytime i run it, the number of lines importing to mysql is different.
It cannot echo success.
When echo the error, some lines it tells me incorrect string values. I thought it was uft-8 problems, but after I just get id and time only, the situation is also the same in point 1
Most importantly, you are not escaping your data. There could be anything in that CSV, breaking that query. Also, you're limiting the line length (so if there are long lines they will not get inserted) and aren't checking for the proper number of columns in the CSV file. Try changing these things:
<?php
$servername = "localhost";
$username = "root";
$password = "abc";
$dbname = "project";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit']))
{
$fname = $_FILES['sel_file']['name'];
echo "Uploaded file name: $fname";
$chk_ext = explode(".",$fname);
if(strtolower(end($chk_ext)) === "csv") {
$sql = "TRUNCATE TABLE datapack";
$conn->query($sql);
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
$head = fgetcsv($handle);
$sql= "INSERT INTO datapack (id, nickname, time, msg) VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
while (($data = fgetcsv($handle)) !== FALSE) {
if (count($data) < 4) {
echo "Error, not 4 columns";
continue;
}
$stmt->bind_param("isss", $data[0], $data[1], $data[2], $data[3]);
if (!$stmt->execute()) {
echo "Error: ". $stmt->error;
} else {
echo "Success!";
}
}
else {
echo "Invalid File";
}
}
?>
<h1>Import CSV file</h1>
<form action="" method="post" enctype="multipart/form-data">
Import File : <input type='file' name='sel_file' size='20'>
<input type='submit' name='submit' value='submit'>
</form>
Note the default HTML behaviour is to post to itself; by needlessly adding $_SERVER["PHP_SELF"] you open yourself up to script injection attacks.
executing 1000 query may be too expensive in small servers.
instead you may do bulk insertion .
$sql= "INSERT into datapack(id,nickname,time,msg) values";
$sqlArray = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sqlArray[] = "('$data[0]','$data[1]','$data[2]','$data[3]')";
}
$sql .= " " . implode(", ", $sqlArray);
mysqli_query($conn,$sql);
echo "Error: ". $conn->error;
However , this would be a great chance to begin using begin_transaction for such a case.
mysqli_begin_transaction
Begins a transaction. Requires MySQL 5.6 and above, and the InnoDB
engine (it is enabled by default). For additional details about how
MySQL transactions work, see ยป
http://dev.mysql.com/doc/mysql/en/commit.html.

Issue in uploading images to MySQL database using PHP

I have this php code to upload image to the database, I have issue
with it and I don't know what is it, the database table name is
images and the fields are id, name VARCHAR(), photo LONGBLOB.
<?php
ini_set('display_errors', '1');
$servername = "";
$username = "";
$password = "";
//$host = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
</br>
</br>
</br>
<input type="submit" name="go" value="Upload"/>
</form>
<?php
if(isset($_POST['go'])){
if(getimagesize($_FILES['image']['tmp_name']) == FALSE){
echo "Select a photo please";
}else {
$image = addslashes($_FILES['image']['tmp_name']);
$name = addslashes($_FILES['image']['name']);
$image = file_get_contents($image);
$image = base64_encode($image);
save_image($image , $name);
}
}
function save_image($image , $name){
$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$conn = new mysqli($servername, $username, $password);
$qry = "insert into images (photo , name) VALUES ('$image','$name')";
$result = mysqli_query($conn,$qry);
if($result){
echo "Successfull upload";
}else{
echo "try Again";
print_r($result);
}
}
?>
</body>
</html>
The result is as shown in the attached screenshot:
Result
Your function neglects to mention the database - you need to supply that as one of the parameters, like:
function save_image($image , $name){
$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$database='xxxxxxxx';/* enter correct db name */
$conn = new mysqli( $servername, $username, $password, $database );
$qry = "insert into images (`photo`, `name`) VALUES ('$image','$name')";
$result = mysqli_query($conn,$qry);
if($result){
echo "Successfull upload";
}else{
echo "try Again";
print_r($result);
}
}
FYI that said your code is vulnerable to sql injection - better to use prepared statements!
You're not using database name in the mysqli constructor. It should be like the following:
$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$database = "database_name_here";
$conn = new mysqli($servername, $username, $password, $database);
Hope it should work now.

Try uploading csv file to mysql using php and mysql

Good day everyone, I am quite new to php and I really need some help. I am trying to upload a csv file to mysql database using php and html form, but it is giving me the following errors:
Notice: Undefined index: temp_name in C:\xampp\htdocs\import csv\importcsv.php on line 23
Warning: fopen(): Filename cannot be empty in C:\xampp\htdocs\import csv\importcsv.php on line 24
Warning: fgetcsv() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\import csv\importcsv.php on line 26
Warning: fclose() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\import csv\importcsv.php on line 30 successfully imported
here is my code
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '';
$db = 'mydb';
$table = 'user';
$conn = mysqli_connect($db_host, $db_user, $db_pwd) or die("Cant connect to database");
if(!mysqli_select_db($conn,$db))
die("Cant select to database");
if(isset($_POST['submit'])){
$fname = $_FILES['sel_file']['name'];
echo 'upload file name: '.$fname.' ';
$chk_ext = explode(".", $fname);
if(strtolower(end($chk_ext)) == "csv"){
$filename = $_FILES['sel_file']['temp_name'];
$handle = fopen($filename, "r");
while(($data = fgetcsv($handle, 1000, ",")) != FALSE){
$sql = "INSERT into user(name,email,phone) values('$data[0]', '$data[1]', '$data[2]')";
mysql_query($sql) or die(mysql_error());
}
fclose($handle);
echo "successfully imported";
}
else{
echo "Invalid file";
}
}
?>
<h1>Import csv file</h1>
<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post' enctype="multipart/form-data">
Import File : <input type='file' name='sel_file' size='20'>
<input type='submit' name='submit' value='submit'>
</form>
Can anyone please help me out
I have updated some lines in your code.
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '';
$db = 'mydb';
$table = 'user';
$conn = mysqli_connect($db_host, $db_user, $db_pwd, $db) or die("Cant connect to database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (isset($_POST['submit'])) {
$fname = $_FILES['sel_file']['name'];
echo 'upload file name: ' . $fname . ' ';
$chk_ext = explode(".", $fname);
if (strtolower(end($chk_ext)) == "csv") {
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle, 1000, ",")) != FALSE) {
$sql = "INSERT into user(name,email,phone) values('".$data[0]."', '".$data[1]."', '".$data[2]."')";
mysqli_query($conn, $sql) or die(mysqli_error($conn));
}
fclose($handle);
echo "successfully imported";
} else {
echo "Invalid file";
}
}
?>
<h1>Import csv file</h1>
<form action='<?php echo $_SERVER["PHP_SELF"]; ?>' method='post' enctype="multipart/form-data">
Import File : <input type='file' name='sel_file' size='20'>
<input type='submit' name='submit' value='submit'>
</form>

if(isset($_POST()) always false

the $_POST array does not get updated for some reason, not sure why.
here is my code, written in a file called database.php:
$user = 'root';
$password = '';
$db = 'comments_schema';
$host = 'localhost:3306';
$mysqli = mysqli_connect('localhost', $user, $password, $db);
$field1_name = "";
if(isset($_POST['field1_name'])) {
$field1_name = $_POST['field1_name'];
}
else {
echo "something is wrong here";
}
$field_name = mysqli_real_escape_string($mysqli, $field1_name);
$sql = 'INSERT INTO parent_comment(commentid, comment) VALUES
('.commentid.', '.$field_name.')';
$result = $mysqli->query($sql);
Here is my index.html portion for that part:
<form action="database.php" method="post">
Comments: <input type="text" name="field1_name"/>
<input type="Submit" name="Submit" value="submit query"/>
</form>
Any reason why isset always returns false in this case?
EDIT: I don't know if this is the case but check your max_input_vars value not to be a low number in php.ini
php_value max_input_vars 6000 //6K is the value you need
//first if checks if the form was submitted first, so you don't always display the error.
if(isset($_POST['Submit'])){
$user = 'root';
$password = '';
$db = 'comments_schema';
$host = 'localhost:3306';
$mysqli = mysqli_connect('localhost', $user, $password, $db);
$field1_name = $_POST['field1_name'] ?? ""; //Use only if you are using PHP 7+ Otherwise leave the code as it was but wrap it inside the outer if.
if(empty($field_name)){
echo "something is wrong here";
}
$field_name = mysqli_real_escape_string($mysqli, $field1_name);
$sql = 'INSERT INTO parent_comment(commentid, comment) VALUES ('.commentid.', '.$field_name.')';
$result = $mysqli->query($sql);
}
More info: https://lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator

Categories