I am trying to add products through PHP inside PHP MySQL but somehow the code is not inserting the data inside the database while running without any errors. I am not sure if there's any mistake in the PHP or in the PHP MySQL. I hope I'll get some answers here. Here's my code:
HTML
<div id="content">
<form method="GET" action="" enctype="multipart/form-data">
<input type="text" name="productName" value="" placeholder="Product Name">
<input type="text" name="quantity" placeholder="Quantity">
<input type="text" name="regularPrice" placeholder="Regular Price">
<input type="text" name="discountedPrice" placeholder="discountedPrice">
<input type="file" name="uploadfile" value="" />
<input type="text" name="category" placeholder="Category">
<div>
<button type="submit" name="productImage">Add Product</button>
</div>
</form>
</div>
PHP CODE:
<?php
error_reporting(0);
?>
<?php
$msg = "";
// If upload button is clicked ...
if (isset($_GET['productImage']))
{
$productName = $_GET['productName'];
$quantity = $_GET['quantity'];
$regPrice = $_GET['regularPrice'];
$discPrice = $_GET['discountedPrice'];
$productImage = $_FILES["uploadfile"]["name"];
$tempname = $_FILES["uploadfile"]["tmp_name"];
$category = $_GET['category'];
$folder = "asset/images/products/".$productImage;
$host = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbname = "kewalsmart";
// Creating Connection
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
if(mysqli_connect_error())
{
die('Connection Error('. mysql_connect_errno().')'. mysqli_connect_error());
}
else
{
$SELECT = "SELECT email From products Where product_name = ? Limit 1";
// Get all the submitted data from the form
$INSERT = "INSERT INTO products (product_name, quantity, regular_price, discounted_price, product_image, category) VALUES ('$productName, $quantity, $regPrice, $discPrice, $productImage, $category')";
// Prepare Statement
$stmt = $conn->prepare($SELECT);
$stmt->bind_param("s", $productName);
$stmt->execute();
$stmt->bind_result($productName);
$stmt->store_result();
$rnum = $stmt->num_rows;
if($rnum==0)
{
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("ssiiss", $productName, $quantity, $regPrice, $discPrice, $productImage, $category);
$stmt->execute();
?>
<script type="text/javascript">
window.alert("Product Added Successfully");
window.location.href = "index.html";
</script>
<?php
}
else
{
?>
<script>
window.alert("Something's Wrong");
setTimeout(function(){ window.location.href = "./"; }, 2000);
</script>
<?php
}
// Now let's move the uploaded image into the folder: image
if (move_uploaded_file($tempname, $folder))
{
$msg = "Image uploaded successfully";
}
else
{
$msg = "Failed to upload image";
}
$stmt->close();
$conn->close();
}
}
?>
Thank you in advance!
Related
I'm trying to figure out how to upload a file into the database where that form contains multiple textfields. I uploaded a BLOB field into the database. So as I try to search the field using the ID number, it will retrieve me the values associated with it. Which works fine, so I added the function of being able to upload a file into that specific id number. I get all sorts of errors and I would like to have an assistance with it. Anyone care to help out? Here are the codes:
<?php
$host = "localhost";
$user = "root";
$password ="";
$database = "ntmadb";
$id = "";
$firstname = "";
$lastname = "";
$username = "";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['firstname'];
$posts[2] = $_POST['lastname'];
$posts[3] = $_POST['username'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM members WHERE id = $data[0]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$username = $row['username'];
}
}else{
echo 'No Data For This Id';
}
}else{
echo 'Result Error';
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `members` SET `firstname`='$data[1]',`lastname`='$data[2]',`username`='$data[3]' WHERE `id` = $data[0]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
}
<!--UPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOAD -->
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'ntmadb');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
// Create the SQL query
$query = "
INSERT INTO `members` (
`data`
)
VALUES (
'{$data}' NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
?>
and here is the html file:
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form action="index4.php" method="post" enctype="multipart/form-data" >
<input type="number" name="id" placeholder="Id" value="<?php echo $id;?>"><br><br>
<input type="text" name="firstname" placeholder="First Name" value="<?php echo $firstname;?>"><br><br>
<input type="text" name="lastname" placeholder="Last Name" value="<?php echo $lastname;?>"><br><br>
<input type="text" name="username" placeholder="User Name" value="<?php echo $username;?>"><br><br>
<div>
<p>
<!-- Input For Edit Values -->
<input type="submit" name="update" value="Update">
<!-- Input For Find Values With The given ID -->
<input type="submit" name="search" value="Find">
</p>
<p>
<input type="file" name="uploaded_file">
<br>
<input type="submit" value="Upload file">
</p>
</div>
</form>
</body>
</html>
Thanks to anyone who can provide me with help. :)
Yahallo! I have a problem in searching the user in the database and displaying them into the textfields. I have set everything to query and search the user by typing the lastname but it gives me an error
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1' .
<?php
$host = "localhost";
$user = "root";
$password ="";
$database = "ntmadb";
$id = "";
$firstname = "";
$lastname = "";
$username = "";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['firstname'];
$posts[2] = $_POST['lastname'];
$posts[3] = $_POST['username'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM members WHERE lastname = $data[2]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$username = $row['username'];
}
}else{
echo 'No Data For This Id';
}
}else{
echo 'Result Error';
}
}
?>
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form action="index44.php" method="post">
<input type="text" name="id" placeholder="Id" value="<?php echo $lastname;?>"><br><br>
<input type="text" name="firstname" placeholder="First Name" value="<?php echo $firstname;?>"><br><br>
<input type="text" name="lastname" placeholder="Last Name" value="<?php echo $lastname;?>"><br><br>
<input type="text" name="username" placeholder="User Name" value="<?php echo $username;?>"><br><br>
<div>
<!-- Input For Edit Values -->
<input type="submit" name="update" value="Update">
<!-- Input For Find Values With The given ID -->
<input type="submit" name="search" value="Find">
</div>
</form>
</body>
</html>
Can someone assist in fixing it? Thank you!
Try below query.
$search_Query = "SELECT * FROM members WHERE lastname = '".$data[2]."'";
Try this:
$temp_lastname = $data[2];
$search_Query = "SELECT * FROM `members` WHERE `lastname` = '$temp_lastname'";
It's a student database system where I can add student data, edit student data, delete student data, and search student data from registration number.
Here is where I'm getting a problem. All is ok but phone number will not be saved in mysql database. All other option are edit and insert in database.
I did not get any error when I edit any information or add new data.
When I submit phone number direct from phpmyadmin then from my index page when I put registration number then get all information of student without phone number.
Here is index.php code:
<?php
$host = "localhost";
$user = "root";
$password ="root";
$database = "college";
$student_reg = "";
$student_name = "";
$father_name = "";
$phone_number = "";
$student_address = "";
$student_course = "";
$student_certificatenumber = "";
$student_email = "";
$student_city = "";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[7] = $_POST['student_reg'];
$posts[1] = $_POST['student_name'];
$posts[2] = $_POST['father_name'];
$posts[3] = $_POST['phone_number'];
$posts[4] = $_POST['student_address'];
$posts[5] = $_POST['student_course'];
$posts[6] = $_POST['student_certificatenumber'];
$posts[8] = $_POST['student_email'];
$posts[9] = $_POST['student_city'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM students WHERE student_reg = $data[7]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$student_reg = $row['student_reg'];
$student_name = $row['student_name'];
$father_name = $row['father_name'];
$phone_number = $row['phone_number'];
$student_address = $row['student_address'];
$student_course = $row['student_course'];
$student_certificatenumber = $row['student_certificatenumber'];
$student_email = $row['student_email'];
$student_city = $row['student_city'];
}
}else{
echo 'No Data For This Id';
}
}else{
echo 'Result Error';
}
}
// Insert
if(isset($_POST['insert']))
{
$data = getPosts();
$insert_Query = "INSERT INTO `students`(`student_reg`, `student_name`, `father_name`, `phone_number`,
`student_address`, `student_course`, `student_certificatenumber`, `student_email`, `student_city`) VALUES ('$data
[7]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[8]','$data[9]')";
try{
$insert_Result = mysqli_query($connect, $insert_Query);
if($insert_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Inserted';
}else{
echo 'Data Not Inserted';
}
}
} catch (Exception $ex) {
echo 'Error Insert '.$ex->getMessage();
}
}
// Delete
if(isset($_POST['delete']))
{
$data = getPosts();
$delete_Query = "DELETE FROM `students` WHERE `student_reg` = $data[7]";
try{
$delete_Result = mysqli_query($connect, $delete_Query);
if($delete_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Deleted';
}else{
echo 'Data Not Deleted';
}
}
} catch (Exception $ex) {
echo 'Error Delete '.$ex->getMessage();
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `students` SET `student_reg`='$data[7]',`student_name`='$data[1]',`father_name`='$data
[2]',`phone_number`='$data[3]',`student_address`='$data[4]',`student_course`='$data
[5]',`student_certificatenumber`='$data[6]',`student_email`='$data[8]',`student_city`='$data[9]' WHERE
`student_reg` = $data[7]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
}
?>
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="student_reg" placeholder="Student Registration Code" value="<?php echo
$student_reg;?>"><br><br>
<input type="text" name="student_name" placeholder="Name" value="<?php echo $student_name;?>"><br><br>
<input type="text" name="father_name" placeholder="Student Father Name" value="<?php echo
$father_name;?>"><br><br>
<input type="text" name="Phone_number" placeholder="Phone Mobile Number" value="<?php echo
$Phone_number;?>"><br><br>
<input type="text" name="student_address" placeholder="Address" value="<?php echo $student_address;?
>"><br><br>
<input type="text" name="student_course" placeholder="Course" value="<?php echo $student_course;?
>"><br><br>
<input type="text" name="student_certificatenumber" placeholder="Certificate Number" value="<?php echo
$student_certificatenumber;?>"><br><br>
<input type="text" name="student_email" placeholder="EMail" value="<?php echo $student_email;?
>"><br><br>
<input type="text" name="student_city" placeholder="City" value="<?php echo $student_city;?>"><br><br>
<div>
<!-- Input For Add Values To Database-->
<input type="submit" name="insert" value="Add">
<!-- Input For Edit Values -->
<input type="submit" name="update" value="Update">
<!-- Input For Clear Values -->
<input type="submit" name="delete" value="Delete">
<!-- Input For Find Values With The given ID -->
<input type="submit" name="search" value="Find">
</div>
</form>
</body>
</html>
check datatype of your phonenumber column in mysql database make it of string type...it may solve your problem
$posts[3] = $_POST['phone_number']
is not the same as
<input type="text" name="Phone_number"
Phone_number is not = to phone_number. PHP is case sensitive.
I have a form (add_company_form.php) in my submit_form_company.php that takes the values from POST and sends them to mysql trough a pdo connection. But I cant get my validation.php to validate the input. I want the user to stay on the same page which is why I dont have a action in the form. The code itself is not complete and there is alot of improvements that can be done, but Im stuck on the validation for now.. Am I on the right track by adding the validation.php before like my db.php?
Submit_form_company.php
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
try {
include('db.php');
include('validation.php');
if(empty($_SESSION["error_message"]) && $_POST['submit_company']) {
$STH = $conn->prepare("
INSERT INTO companies (Name,Notes,OrganizationNumber)
VALUES (:Name,:Notes,:OrganizationNumber)");
$STH->bindParam(':Name', $_POST['Name'], PDO::PARAM_STR);
$STH->bindParam(':Notes', $_POST['Notes'], PDO::PARAM_STR);
$STH->bindParam(':OrganizationNumber', $_POST['OrganizationNumber'], PDO::PARAM_INT);
$STH->execute();
} elseif ($_SESSION["error_message"] && $_POST['submit_edit']) {
foreach ($_POST['company'] as $i => $value) {
$STH = $conn->prepare("
UPDATE companies
SET Name = :Name,Notes = :Notes,OrganizationNumber = :OrganizationNumber
WHERE Id = :Id");
$STH->bindParam(':Id', $value['Id'], PDO::PARAM_INT);
$STH->bindParam(':Name', $value['Name'], PDO::PARAM_STR);
$STH->bindParam(':Notes', $value['Notes'], PDO::PARAM_STR);
$STH->bindParam(':OrganizationNumber', $value['OrganizationNumber'], PDO::PARAM_INT);
$STH->execute();
}
}
if(empty($_SESSION["error_message"])){
echo "<meta http-equiv='refresh' content='0'>";
}
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
require("add_company_form.php");
$DBH = null;
?>
add_company_form.php
<div class="row">
<form class="col-md-4 navbar-form" method="POST" action="" enctype="multipart/form-data">
<div class="form-group">
<label class="sr-only" for="Name">Name:</label> <input type="text" class="form-control" name="Name" placeholder="Name"><br />
<label class="sr-only" for="Notes">Notes:</label> <input type="text" class="form-control" name="Notes" placeholder="Notes"><br />
<label class="sr-only" for="OrganizationNumber">OrganizationNumber:</label> <input type="text" class="form-control" name="OrganizationNumber" placeholder="OrganizationNumber"><br />
<input type="submit" name="submit_company" class="btn btn-default" value="Submit">
</div>
</form>
<?php
if(!empty($_SESSION["error_message"])){
echo'<div id="error_message" class="col-md-8">';
print_alert_error($_SESSION["error_message"]);
$_SESSION["error_message"] = "";
echo'</div>';
} ?>-
Validation.php
<?
$error = "";
if(isset($_POST['submit_company'])) {
$name = $_POST['Name'];
$notes = $_POST['Notes'];
$organization_number = $_POST['OrganizationNumber'];
if (!ctype_alpha(str_replace(array("'", "-"), "",$name))) {
$error .= '<p class="error">Name should be alpha characters only.</p>';
}
}
//Add error message to session
if (!empty($error)){
$_SESSION["error_message"] = $error;
}
?>
DB.php
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "test";
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>
A silly suggestion but try using the full <?php opening tag in your validation.php file.
I'm pretty sure my code is correct. The issue I have is that, when viewing the image, there is only some of the image that is showing. I think it has something to do with my database that i'm uploading to, but I can't figure out what
Here is my code:
form for the upload
<form id="form2" method="post" name="postForm" action="post.php" enctype="multipart/form-data">
<h2>Post News here</h2>
<p>Title:</p>
<input type="text" required placeholder="Enter a title" maxlength="30" name="postTitle">
<p>Body:</p>
<input type="textarea" required placeholder="Enter a body" maxlength="250" name="postBody">
<p>Link/ Reference:</p>
<input type="text" required placeholder="Enter a link or reference" maxlength="100" name="postLinkRef">
<p>Image to upload:</p>
<input type="file" name="imageTest">
<p><input type="submit" value="Submit" name="submit"></p>
</form>
inserting the image
<?php
$host = "localhost";
$userName = "root";
$password = "password";
$db = "userdata";
$connect = mysqli_connect($host,$userName,$password, $db);
if($connect)
{
if(isset($_POST['submit']) && isset($_FILES['imageTest']))
{
$postTitle = mysqli_real_escape_string($connect,$_POST['postTitle']);
$postBody = mysqli_real_escape_string($connect,$_POST['postBody']);
$postLink = mysqli_real_escape_string($connect,$_POST['postLinkRef']);
//address, postcode
//admin priveleges for scertain accounts
//wont allow me to use $_FILES and i dont know why...
$postImageName = mysqli_real_escape_string($connect, $_FILES['imageTest']['name']);
$postImageData = mysqli_real_escape_string($connect, file_get_contents($_FILES["imageTest"]["tmp_name"]));
$postImageType = mysqli_real_escape_string($connect, $_FILES["imageTest"]["type"]);
$sql = "INSERT INTO news(title, body, link, imageName, imageData) VALUES('$postTitle','$postBody','$postLink','$postImageName','$postImageData')";
if(mysqli_query($connect, $sql))
{
echo "Your post has been uploaded\n\n";
echo "Thank you for your post $testUserName\n\n";
echo "<a href='index.php'>Got to your news </a>";
}
else
{
echo "Sorry, something went wrong!! Check to make sure the image your are uploading is a jpeg image (not any other file)!";
}
}
mysqli_close($connect);
}
else
{
echo "Fail connection";
}
?>
Showing the image
<?php
$host = "localhost";
$userName = "root";
$password = "password";
$db = "userdata";
$connect = mysqli_connect($host,$userName,$password, $db);
if(isset($_GET['postID']))
{
$id = mysqli_real_escape_string($connect, $_GET['postID']);
$q = "SELECT * FROM news WHERE postID = $id";
$r = mysqli_query($connect, $q);
if(mysqli_num_rows($r)==1)//id found in the table
{
$row = mysqli_fetch_assoc($r);
$imageData = $row["imageData"];
}
header("Content-type:image/jpeg");
echo $imageData;
}
else
{
echo "error";
}
?>
[1[2