This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 5 years ago.
I am using the code below i need to check the description must not be same so i have to check the description column for duplicate entry how to do this ?
<?php
session_start();
require 'Admin/includes/connection.php';
$emp_id = $_SESSION['id'];
$task_name = $_POST['task_name'];
$desc = $_POST['desc'];
$hours = $_POST['hours'];
$t = "random";
$a = date('Y-m-d');
$sql = "INSERT INTO project_task (emp_id, task_type, task, description, hours, submit_date) VALUES ('$emp_id', '$t', '$task_name', '$desc', '$hours', '$a')";
if($conn->query($sql) === TRUE){
$data["abc"] = "true";
}
else{
$data["abc"] = "false";
}
header("Content-type: application/json");
echo json_encode($data);
?>
This Will Help You
<?php
session_start();
require 'Admin/includes/connection.php';
$emp_id = $_SESSION['id'];
$task_name = $conn->real_escape_string($_POST['task_name']);
$desc = $conn->real_escape_string($_POST['desc']);
$hours = $_POST['hours'];
$t = "random";
$a = date('Y-m-d');
$q = "SELECT description from project_task where description = '$desc' ";
$result = $conn->query($q);
if($result->num_rows > 0 ){
$data["result"] = "false";
}else{
$sql = "INSERT INTO project_task (emp_id, task_type, task, description, hours, submit_date) VALUES ('$emp_id', '$t', '$task_name', '$desc', '$hours', '$a')";
if($conn->query($sql) === TRUE){
$data["result"] = "true";
}
else{
$data["result"] = "false";
}
}
header("Content-type: application/json");
echo json_encode($data);
?>
Related
This question already has answers here:
How can I do 'insert if not exists' in MySQL?
(11 answers)
Closed 2 years ago.
I have a database that contains more than 640,000 records that I update every week with data from a JSON file. What I want to do is only load records into the database that do not currently exists. My script below works on small amounts of data but when I try to load a large file it times out (I get a 500 Internal Server Error). Is there a better way to do this?
<?php
set_time_limit(0);
ini_set('memory_limit','2000M');
$url = 'json/OERrecordstest.json';
$contents = file_get_contents($url);
$records = json_decode($contents, true);
include("../config.php");
echo "<div class='card card-body'>";
foreach($records as $record) {
$type = $record['type'];
$name = $record['title'];
$title = addslashes($name);
$creator = $record['author'];
$author = addslashes($creator);
$link = addslashes($record['link']);
$origin = $record['source'];
$source = addslashes($origin);
$description = addslashes($record['description']);
$base_url = $record['base_url'];
$isbn_number = $record['isbn_number'];
$e_isbn_number = $record['e_isbn_number'];
$publication_date = $record['publication_date'];
$license = $record['license'];
$subject = addslashes($record['subject']);
$image_url = $record['image_url'];
$review = $record['review'];
$language = $record['language'];
$license_url = $record['license_url'];
$publisher = addslashes($record['publisher']);
$publisher_url = $record['publisher_url'];
$query = $conn->prepare("SELECT * FROM oer_search WHERE title=:title AND author=:author AND source=:source");
$query->bindParam(":title", $name);
$query->bindParam(":author", $creator);
$query->bindParam(":source", $origin);
$query->execute();
if ($query->rowCount() == 0) {
$insert = $conn->prepare("INSERT INTO oer_search (type, title, author, link, source, description, base_url, isbn_number, e_isbn_number, publication_date, license, subject, image_url, review, language, license_url, publisher, publisher_url) VALUES ('$type', '$title', '$author', '$link', '$source', '$description', '$base_url', '$isbn_number', '$e_isbn_number', '$publication_date', '$license', '$subject', '$image_url', '$review', '$language', '$license_url', '$publisher', '$publisher_url')");
$insert->execute();
}
}
if($insert){
echo "<p><span class='recordInserted'><em>$name was successfully inserted into SOAR.</em></span></p>";
}
else {
echo "<p><span class='recordInserted'><em>Record(s) already exist in SOAR.</em></span></p>";
}
echo "</div>";
?>
I could not comment, I wrote as an answer because my score was not enough. can you change it like this and try it?
$query = $conn->prepare("SELECT id FROM oer_search WHERE title=:title AND author=:author AND source=:source limit 1");
or
<?php
if(!session_id()) session_start();
ini_set('memory_limit', '2000M');
$url = 'json/OERrecordstest.json';
$contents = file_get_contents($url);
$records = json_decode($contents, true);
include("../config.php");
echo "<div class='card card-body'>";
if (!$_SESSION["records"]) {
foreach ($records as $record) {
$_SESSION["records"][$record["id"]] = $records;
}
}
$i = 0;
foreach ($_SESSION["records"] as $record) {
$i++;
if ($i > 1000) break;
$type = $record['type'];
$name = $record['title'];
$title = addslashes($name);
$creator = $record['author'];
$author = addslashes($creator);
$link = addslashes($record['link']);
$origin = $record['source'];
$source = addslashes($origin);
$description = addslashes($record['description']);
$base_url = $record['base_url'];
$isbn_number = $record['isbn_number'];
$e_isbn_number = $record['e_isbn_number'];
$publication_date = $record['publication_date'];
$license = $record['license'];
$subject = addslashes($record['subject']);
$image_url = $record['image_url'];
$review = $record['review'];
$language = $record['language'];
$license_url = $record['license_url'];
$publisher = addslashes($record['publisher']);
$publisher_url = $record['publisher_url'];
$query = $conn->prepare("SELECT id FROM oer_search WHERE title=:title AND author=:author AND source=:source limit 1");
$query->bindParam(":title", $name);
$query->bindParam(":author", $creator);
$query->bindParam(":source", $origin);
$query->execute();
if ($query->rowCount() == 0) {
$insert = $conn->prepare("INSERT INTO oer_search (type, title, author, link, source, description, base_url, isbn_number, e_isbn_number, publication_date, license, subject, image_url, review, language, license_url, publisher, publisher_url) VALUES ('$type', '$title', '$author', '$link', '$source', '$description', '$base_url', '$isbn_number', '$e_isbn_number', '$publication_date', '$license', '$subject', '$image_url', '$review', '$language', '$license_url', '$publisher', '$publisher_url')");
$insert->execute();
unset($_SESSION["records"][$record["id"]]);
}
}
print "remaining data :". count($_SESSION["records"]);
?>
Tipps to speed up mass-imports:
Move your SQL prepare outside of the loop (you only have to do it once)
Collect data to insert into batches of 1000 (for example.. usually alot more possible)
Use transactions / disable Index calculation during insert
Find duplicates with a lookup array from existing data (don't query the database for each row of your import)
In general: Avoid SQL queries in Loops
hope that helps a bit
I'm currently working on a database where I would like the order_ID's to be put into two tables. This works but the issue I have is that the loop is only iterating once. If anyone could help and explain where I have gone wrong it would be greatly appreciated.
session_start();
echo $_SESSION['shop_id'];
$shopid = $_SESSION['shop_id'];
$username = $_SESSION['username'];
$con = mysqli_connect('localhost', 'root', '', 'aurora');
if (!isset($con)) {
echo "Connection to Aurora System failed.";
}
if (isset($_POST['items'])) {
echo "True";
} else {
echo "false";
}
$valid = true;
$date = date('l jS \of F Y h:i:s A');
$sql2 = "INSERT INTO orders_new (user_submitted, order_date, customer_ID) VALUES ('$username', '$date', '$shopid')";
if ($valid == true) {
$ordersubmit2 = mysqli_query($con, $sql2);
echo "Success!";
}
$count = $_POST['items'];
for ($i = 1; $i <= $count; $i++) {
$idinsert = mysqli_insert_id($con);
$product = $_POST['product'.$i];
$nicotine = $_POST['nicotine'.$i];
$qty = $_POST['qty'.$i];
echo $product;
$sql = "INSERT INTO orders_detail (orders_id ,product, variant, quantity) VALUES ('$idinsert', '".$product."', '".$nicotine."', '".$qty."')";
$ordersubmit = mysqli_query($con, $sql);
}
Was my own fault, the order_id was a primary key hence the loop stopping due to only allowing unique values.
just want to add record if count of column is less than 2 for today's date and if count is more than two it should not get insert into the db.It's keep getting added after two records.
$user_ip = getenv('REMOTE_ADDR');
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip"));
$city = $geo["geoplugin_city"];
$region = $geo["geoplugin_regionName"];
$img = $_POST['img'];
$amount = 5;
$sql = "SELECT COUNT(*) as totalupload FROM `daily_uploads` WHERE DATE_FORMAT(`date`, '%Y-%m-%d') = CURDATE()";
$row = mysqli_fetch_assoc($sql);
$sum = $row['totalupload'];
if ($sum < 2 ) {
$sql = "INSERT INTO `daily_uploads` (img, geoplugin_city, geoplugin_regionName, amount)
VALUES ('$img', '$city', '$region','$amount')";
if ($conn->query($sql)) {
echo ('success');
} else {
echo ('error');
}
} else {
echo"already exist";
make the connection after count query like this,
$result = mysqli_query($con,$sql);
Try this one hope it will help you.
$user_ip = getenv('REMOTE_ADDR');
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip"));
$city = $geo["geoplugin_city"];
$region = $geo["geoplugin_regionName"];
$img = $_POST['img'];
$amount = 5;
$sql = "SELECT COUNT(*) as totalupload FROM `daily_uploads` WHERE DATE_FORMAT(`date`, '%Y-%m-%d') = CURDATE()";
$qry= mysql_query($sql);
$row = mysql_fetch_assoc($qry);
$count = $row['totalupload'];
if ($count < 2 ) {
$sql = "INSERT INTO `daily_uploads` (img, geoplugin_city, geoplugin_regionName, amount)
VALUES ('$img', '$city', '$region','$amount')";
if ($conn->query($sql)) {
echo ('success');
} else {
echo ('error');
}
} else {
echo"already exist";
I am having some problems with checking if the field is empty or not in SQL using PHP without using mysql_fetch_array().
I have this code:
date_default_timezone_set('Asia/Taipei');
$remarks = $_POST['remarks'];
$date_added = date ("Y-m-d");
$time_added = date ("h:i:s a");
$lname = $_SESSION['user']['last_name'];
$fname = $_SESSION['user']['first_name'];
$minitial = $_SESSION['user']['middle_initial'];
$con = mysqli_connect("localhost", "root", "", "thisdb");
if(empty(`TIME_IN_1`)) {
$query = "INSERT INTO time_logs (LAST_NAME, FIRST_NAME, MIDDLE_INITIAL, DATE, TIME_IN_1, TIME_IN_1_REMARKS) VALUES('$lname', ' $fname', '$minitial', '$date_added', '$time_added', '$remarks')";
}
else {
$query = "UPDATE time_logs SET TIME_IN_2 = '$time_added' where LAST_NAME = '$lname' AND DATE = '$date_added'";
}
$save = mysqli_query($con, $query);
header("Location: time_in_complete.php");
What I basically want to accomplish is if the TIME_IN_1 field is empty, the data will be added there. If it is not empty, then the data will be added to the TIME_IN_2.
Apprently, this line:
if(empty(`TIME_IN_1`))
doesn't seem to work.
$first_query = "SELECT TIME_IN_1 FROM time_logs WHERE LAST_NAME = '" . $lname . "' AND FIRST_NAME = '" . $fname . "'";
$data = mysqli_query($con, $first_query);
$num_row = mysqli_num_rows($data);
if($num_row == 0) {
$query = "INSERT INTO time_logs (LAST_NAME, FIRST_NAME, MIDDLE_INITIAL, DATE, TIME_IN_1, TIME_IN_1_REMARKS) VALUES('$lname', ' $fname', '$minitial', '$date_added', '$time_added', '$remarks')";
}
else {
$query = "UPDATE time_logs SET TIME_IN_2 = '$time_added' where LAST_NAME = '$lname' AND DATE = '$date_added'";
}
$save = mysqli_query($con, $query);
header("Location: time_in_complete.php");
Try a query like:
SELECT TIME_IN_1 from time_logs where LAST_NAME = '$lname' AND DATE = '$date_added'
Then:
// Default to true and set this false if we find a value
$bIsEmpty = true;
// Check if any rows match
if ($result->num_rows > 0){
// Yes a row matches, so check if we have a value
$row = $result->fetch_object();
if ($row->TIME_IN_1 != "")
$bIsEmpty = false;
}
if ($bIsEmpty === true){
// Do your insert
} else {
// Do your update
}
I would appreciate it if anyone willing to tell how to echoing /print.
Below is the process of entering data into the database, before inserting it how can I echoing it to the table?
<?php
session_start();
if(isset($_POST['submit']))
{
include('class/stock_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
$from = mysql_real_escape_string(stripslashes($_POST['from']));
$value = floatval($_POST['amount']);
$date = date('Y-m-d H:i:s');
$_SESSION['selected'] = $from;
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
$st->convert($from,$key,$date);
$stc_price = $st->price($value);
$stock = mysql_real_escape_string(stripslashes($stock));
$count = "SELECT * FROM oc_stock WHERE stock = '$key'";
$result = mysql_query($count) or die(mysql_error());
$sql = '';
if(mysql_num_rows($result) == 1)
{
$sql = "UPDATE oc_stock SET stock_title = '$stock', stc_val = '$stc_price', date_updated = '$date' WHERE stock = '$key'";
}
else
{
$sql = "INSERT INTO oc_stock(stock_id,stock_title,stock,decimal_place,stc_val,date_updated) VALUES ('','$stock','$key','2',$stc_price,'$date')";
}
$result = mysql_query($sql) or die(mysql_error().'<br />'.$sql);
}
header("Location: index.php");
exit();
}
?>
Insert this:
echo "<table><tr><th>".implode(array_keys($stocks), '</th><th>')."</th></tr>";
foreach($stocks as $row) echo "<tr><td>".implode('</td><td>', $row)."</tr>";
echo "</table>";
Edit: If printing the data is the goal and the table-view is not important, I recommend print_r($stocks) instead.