PHP/MySQL Insert distinct array values - php

I am inserting values into a MySQL table using the code below, and I need to prevent users from inserting the same priority value for each studentname more than once. What is the best way to do this please?
This is the table:
id studentname title academicdiscipline priority
012345678 TEST, NAME Test title 1 Civil 1
012345678 TEST, NAME Test title 2 Civil 2
012345678 TEST, NAME Test title 3 Civil 3
012345678 TEST, NAME Test title 4 Civil 4
012345678 TEST, NAME Test title 5 Civil 5
Code:
if(isset($_POST['submit']) && !empty($_POST['submit'])) {
$ids = $_POST['id'];
$names = $_POST['studentname'];
$titles = $_POST['title'];
$disciplines = $_POST['academicdiscipline'];
$priorities = $_POST['priority'];
foreach($priorities as $key => $priority) {
if ($priority > 0) {
$query = "INSERT INTO flux_project_selection (id, studentname, title, academicdiscipline, priority)
VALUES ( " . mysql_real_escape_string($ids[$key]) . ",
'" . mysql_real_escape_string($names[$key]) . "',
'" . mysql_real_escape_string($titles[$key]) . "',
'" . mysql_real_escape_string($disciplines[$key]) . "',
" . mysql_real_escape_string($priority) . " )";
$retval = mysql_query($query) or die(mysql_error());
}
}
echo "<p> Added.</p><br />";
}

Create index for unique record, using combination of fields
ALTER TABLE table_name ADD UNIQUE INDEX index_name (field1, field2);
it will allow you to add first record but on duplicate entry show Duplicate entry ... for unique index. You can either use try and catch to display error message or use on duplicate update record if your project has this requirement.

query for the max priority for the student then increment it with 1.
$queryMaxPriority = 'select max(priority) from flux_project_selection where id = STUDENT_ID;
$priority_no = $queryMaxPriority + 1;
i used this in some of my apps i developed.
Update
$priority = 'select count(priority) from flux_project_selection where id = STUDENT_ID and priority = PRIORITY';
if (count($priority>0)){
//send some error message in your page.
}

Related

Select ID from one table and insert in another table with while loop

The code below works on three tables:
iStock, iInvoicebook, iInvoiceitems
iInvoicebook and iInvoiceitems are linked bt ID and dInvoicebookFKEY,
iStock - This table stores all products with clients name and quantity. To generate an invoice, the code gets DISTINCT clients and inserts to iInvoicebook.
After this, the code inserts all product details from the iStock table to iInvoiceitems.
The code below mostly works, except that when I try to get iInvoicebook ID and try to insert it (as foreign key) in iInvoiceitems, it inserts the old ID of iInvoicebook based on clientID.
I want the newly added ID of iInvoicebook to be inserted in iInvoiceitems.
if($CurrDate == $LastDayofMonth)
{
// Get Distinct clients and add it into Main table "Invoicebook"
$getClients = "SELECT DISTINCT iClientName AS CLT, Product from stock where quantity > '0' AND InvoiceDate ='$LastDayCM'";
$stmt = ExecuteQuery($getClients); // execute the query
if ($stmt->rowCount() > 0) { // check condition: if record count is greater than 0
while ($row = $stmt->fetch()) { // begin of loop
$NewNo = Executerow("Select max(ibInvoiceNo) AS NEXTNO from invoicebook");
$Nor = $NewNo["NEXTNO"] + 1 ;
$instInInvoice = ExecuteStatement("INSERT INTO invoicebook (ibClientName, Product, InvoiceNo)
Values( '".$row["CLT"]."','".$row["Product"]."', '".$Nor."')");
}
}
// Now no Disticnt value. Get all stock values of related client and insert into "invoiceitems" table
$getDetails = "select iClientID, product, quantity from stock where quantity > '0' AND InvoiceDate ='$LastDayCM' AND iClientName = '".$getClients["iClientName"]."'";
$dstmt = ExecuteQuery($getDetails); // execute the query
if ($dstmt->rowCount() > 0) { // check condition: if record count is greater than 0
while ($row = $dstmt->fetch()) { // begin of loop
$InvoiceFKEY = Executerow("Select INVID from invoicebook where dClientID = '".$row["iClientID"]."'");
$DetailsInsrt = ExecuteStatement("INSERT INTO invoiceitems (dproduct, dQuantity, dRate, dInvoicebookFKEY)
Values( '".$row["product"]."','".$row["quantity"]."','".$rate."', '".$InvoiceFKEY["INVID"]."')");
}
}
}
here your code with some comments :
if ($CurrDate == $LastDayofMonth) {
// Get Distinct clients and add it into Main table "Invoicebook"
$getClients = "SELECT DISTINCT iClientName AS CLT, Product from stock where quantity > '0' AND InvoiceDate ='$LastDayCM'";
$stmt = ExecuteQuery($getClients); // execute the query
if ($stmt->rowCount() > 0) { // check condition: if record count is greater than 0
while ($row = $stmt->fetch()) { // begin of loop
$NewNo = Executerow("Select max(ibInvoiceNo) AS NEXTNO from invoicebook");
$Nor = intval($NewNo["NEXTNO"]) + 1;
$instInInvoice = ExecuteStatement("INSERT INTO invoicebook (ibClientName, Product, InvoiceNo) "
. " Values ( '" . $row["CLT"] . "','" . $row["Product"] . "', '" . $Nor . "') "
. " on duplicate key update InvoiceNo='{$Nor}'"); //EDIT : Dont know but should get PK key
// => this could generate multiple line in you DB
// => and don't know your DB structure but for me, should be better to link with stock.iClientID than stock.iClientName
//
}
}
/**
* From here why create second loop?
* Should have fonction "get_last_id" from your DB object and if the field invoicebook.INVID is AI should get last one
*
*/
// Now no Disticnt value. Get all stock values of related client and insert into "invoiceitems" table
$getDetails = "select iClientID, product, quantity from stock where quantity > '0' AND InvoiceDate ='$LastDayCM' "
. " AND iClientName = '" . $getClients["iClientName"] . "'"; // - EDIT : this is empty var => NULL
$dstmt = ExecuteQuery($getDetails); // execute the query
if ($dstmt->rowCount() > 0) { // check condition: if record count is greater than 0
while ($row = $dstmt->fetch()) { // begin of loop
$InvoiceFKEY = Executerow("Select INVID from invoicebook where dClientID = '" . $row["iClientID"] . "'");
$DetailsInsrt = ExecuteStatement("INSERT INTO invoiceitems (dproduct, dQuantity, dRate, dInvoicebookFKEY)
Values( '" . $row["product"] . "','" . $row["quantity"] . "','" . $rate . "', '" . $InvoiceFKEY["INVID"] . "')");
//Same : duplicate key => what the frequence of this routine?
// ($CurrDate == $LastDayofMonth) => I guess once by day, everyday and run only last month day
// Or action from you : mean you can run this script more than once a day => duplicated data
// $LastDayCM == $CurrDate == $LastDayofMonth ??????
}
}
}
If I understand well, you should maybe change your function with a code like this :
if ($CurrDate == $LastDayofMonth) {
//First should escape your variable
$getClients = sprintf("SELECT DISTINCT `iClientName` AS CLT,`iClientID` as 'IdClient', `Product`,`quantity` " // should
. " from `stock` "
. " where `quantity`>%d AND InvoiceDate='%s' "
, 0 // quantity
, escapeFunction($LastDayCM) //mysqli_real_escape($linkSql, $LastDayCM) : don't know where your data come from
);
$stmt = ExecuteQuery($getClients); // execute the query
if ($stmt->rowCount() > 0) { // Useless for me
while ($row = $stmt->fetch()) { // begin of loop
$NewNo = Executerow("Select max(`ibInvoiceNo`) AS NEXTNO from `invoicebook`");
$Nor = intval($NewNo["NEXTNO"]) + 1; // NEXTNO can be null if no data
$instInInvoice = ExecuteStatement(
sprintf("INSERT INTO `invoicebook` (`dClientID`,`ibClientName`, `Product`, `InvoiceNo`) "
. " Values (%d, '%s','%s', %d) "
, $row['IdClient'] // add ID ??? and not sure about column name
, escapeFunction($row["CLT"])
, escapeFunction($row["Product"])
, $Nor
)
);
//Get last id 2 options : get_last_id function or new select statement :
//option 1 : better
$INVID = getLastIdFunction();
//Option 2 : depend of your DB structure
$InvoiceFKEY = Executerow(
sprintf("Select INVID from `invoicebook`"
. " where dClientID =%d and InvoiceNo=%d"
, $row['IdClient']
, $Nor
)
);
$tmpStatement = ExecuteQuery($InvoiceFKEY); // execute the query
$INVID = $tmpStatement->fetch()['INVID'];
//Add new invoiceitems
$DetailsInsrt = ExecuteStatement(sprintf("INSERT INTO `invoiceitems` "
. " (`dproduct`, `dQuantity`, `dRate`, `dInvoicebookFKEY`) Values "
. " ( '%s',%d,%0.2f, %d)"
, escapeFunction($row["Product"])
, $row["quantity"]
, $rate // where come from? format? 00000.00 ???
, $INVID
)
);
ExecuteQuery($DetailsInsrt);
}
}
}
Without DB structure and more details, hard to go further

PHP multi update mysql bug about input[type=checkbox]

I used JS set the checkbox value to '1' or '0' : this js
multi update mysql. this is a page can multi update all a website menu table
is multi update. these code can update every columns. but blank cannt update.
Why?
sometime if show 5 records.
I set 3,4,5 record to blank = 1;
maybe 1,2,3 will be change to blank = 1.
so confused about that
and I confirmed html is set to name="blank[]"
or what's I missed?
if (isset($_POST["edit_menu"])) {
$gid =$_POST["gid"];
$sql = "";
$menuCount = count($_POST["id"]);
for($i=0;$i<$menuCount;$i++) {
$title = $_POST["title"];
$url = $_POST["url"];
$id = $_POST["id"];
$blank = $_POST["blank"];
$sql .= "UPDATE `menu` set
title='" . $title[$i] . "',
url='" . $url[$i] . "',
blank='" . $blank[$i] . "'
WHERE id='" . $id[$i] . "' AND gid = '$gid';";
}
$stmt = $pdo->exec($sql);
}
This is a detailed test results (3 records)
If three records are set blank = 1
This is successful
If three records are set blank = 0
This is successful
If only id: 1 set a record blank = 1
This is successful
If id: 2 Record Set blank = 1
The results will be id: 1 to blank = 1
id: 2 update failed
If id: 3 Record Set blank = 1
The results will be id: 1 to blank = 1
id: 3 update failed

Can't get score to update with this mysql statement

I'm guessing that I'm just a little rusty or something because it seems like this should be working. Am I missing something here...
Here is the code I am trying to use...
<?php
echo dbConn();
$existing_time = mysql_result(mysql_query("SELECT p_time FROM scores WHERE p_uid=$uid"), 0);
$existing_category = mysql_result(mysql_query("SELECT p_cat FROM scores WHERE p_uid=$uid AND p_cat=$pieces"), 0);
if ($existing_category == "") {
mysql_query(
"INSERT INTO scores VALUES (
'',
'$uid',
'$pusername',
'$time',
'$pieces'
)");
} elseif ($existing_time <= $time) {
echo "No Change! Old Score Was Better (Lower)";
} elseif ($existing_time > $time) {
mysql_query("UPDATE scores SET p_time = " . $time . " WHERE p_uid = " . $uid . " AND p_cat = " . $pieces . "");
};
?>
Now... Here is what I am trying to do...
I am collecting info from the database where the users username AND category match. If the category for that user does not exist, it inserts the latest score. (This much works.)
Then, if the category does exist but the old score is better, it just does nothing. (This part works too)...
However, what I can't seem to do is get it to update the last score, if the current score is better (lower score, since this is a time based game.) It doesn't update the score.
I am trying it this way: By updating a row in "scores" where the USERNAME and the CATEGORY match at the same time.
Please note... where it says "pieces". this is a category. Where it says "time", this is a score. The score is returned as 00:00:00 for hours minutes and seconds.
EXAMPLE: (in parentheses is the database row name)
id (ID) = just KEY id in sequencial order
user id (p_uid) = 123456789
username (p_username) = somename
score (p_time) = 00:01:03
category (p_cat) = 10
Change you update statement to:
mysql_query("UPDATE scores SET p_time = '" . $time . "' WHERE p_uid = " . $uid . " AND p_cat = " . $pieces . "");
You have missed quotes in the update statement around $time.

Mysql Insert data to table with duplicate data except one field

I am developing a classroom website.
There is a form to insert student profile/data into the database table student.
This site has 5 class groups, IDs as id= 1, 2, 3, 4, 5.
Inserting data to database table succeeds.
But I have a question: Each student must be under classroom 1 and 2, so when we insert data I need the database to automatically create two database results for each times, both results all field are same data except classgroup_id, i mean one result must classgroup_id=1 and second result must be classgroup_id=2, i need mysql automatically generated this for when add each student... any idea.?
this is my table structure
student_id (int) AI
name
email
classgroup_id (default value=1)
user_id
this is my php code for insert data to table
$this->db->query("INSERT INTO " . DB_PREFIX . "student SET user_id = '" . (int)$this->user->getId() . "', name = '" . $this->db->escape($data['name']) . "', email = '" . $this->db->escape($data['email']) . "'");
thanks... i have only a medium level php knowledge
ClassGroups are in table or just static numbers?
If they are just static numbers, then i think simpliest way is to do another insert with duplicated data. For example for both rows should be:
$this->db->query("INSERT INTO " . DB_PREFIX . "student SET user_id = '" . (int)$this->user->getId() . "', name = '" . $this->db->escape($data['name']) . "', email = '" . $this->db->escape($data['email']) . "'");
$this->db->query("INSERT INTO " . DB_PREFIX . "student SET user_id = '" . (int)$this->user->getId() . "', name = '" . $this->db->escape($data['name']) . "', email = '" . $this->db->escape($data['email']) . "', classgroup_id =2");
If they are in some table, then you can do insert with one insert(code will be shorter) but with different insert syntax then yours. For example your ClassGroup table is just ClassGroups:
$this->db->query("INSERT INTO " . DB_PREFIX . "student (user_id, name, email, ClassGroup_id)
select " . (int)$this->user->getId() . ", '" . $this->db->escape($data['name']) . "', '" . $this->db->escape($data['email']) . "',ClassGroup_id from ClassGroups where ClassGroup_id=1 or ClassGroup_id=2");
But i think it should be best if you do for each data(student, ClassGroup) different table and do relation table for them, it will not duplicate data and table student will be faster if you gather data from it by primary AI key and not by varchar type column name.
You don't need PHP to do this... Pure SQL pseudosolution:
INSERT INTO student (student_id name, email) SELECT name, email from student where classgroup_id = ?
If you construct a fiddle and leave a comment as to where to find said fiddle, I'd be happy to tweak the query for your specific needs.
In order to avoid duplicate entries for students, you can make another table in which you link the students to their classes.
For example:
Students
student_id (primary key)
name
email
user_id (if still needed...)
Classgroups
classgroup_id (primary key)
classgroup_name
StudentsPerClassgroup
student_id (foreign key)
classgroup_id (foreign key)
You have to keep the record in temporary table first and then do the operations .. try it
//get last insertId
$last_insert_id = $this->db->insert_id();
$new_id = $last_insert_id +1;
$query = "CREATE TEMPORARY TABLE tmp SELECT * FROM yourtable WHERE your_primary_key = $last_insert_id;
UPDATE tmp SET your_primary_key= $new_id,classgroup_id = 2 WHERE your_primary_key = $last_insert_id;
INSERT INTO yourTable SELECT * FROM tmp WHERE your_primary_key = new_id";
$this->db->query($query);
Hope you get some idea

Insert form data into two database tables

I am looking to post data into two database tables from a single form.
My databases are arranged as below:
Database 1 - 'watchlists':
watchlist_id
user_id
name
description
category
Database 2 - 'watchlist_films':
watchlist_id
film_id
My current MySQL query looks like this: $query = "INSERT INTO watchlist_films (watchlist_id, film_id) VALUES ('$watchlist_name['watchlist_id']', '$rt_id') WHERE watchlists ('watchlist_id') = " . $watchlist_name['watchlist_id'];, but I'm not sure if there's got to be some form of INNER JOIN somewhere?
Not sure what other information/code to provide, so I apologise if there's too little detail here, but, if there's anything else which is needed, just drop me a comment and I'll put up anything else which is required. I'm a relative PHP newbie, so apologies if this seems like a really simple question!
Update based on comments:
I have now got half of my query working, and have updated the logic to reflect it. The new query is basically doing the following:
INSERT new Watchlist to 'watchlists' table
SELECT watchlist_id of new Watchlist from 'watchlists' table WHERE watchlist_name = $watchlist_name (name of new Watchlist just created) and user_id = $user_id
INSERT watchlist_id (selected from previous query) AND film_id into 'watchlist_films' table
based on your comments, my queries now look like so:
if ($submit == 'Submit') {
require_once("db_connect.php");
$watchlist_name = clean_string($_POST['watchlist-name']);
$watchlist_description = clean_string($_POST['watchlist-description']);
$watchlist_category = $_POST['watchlist-category'];
$addWatchlist_bad_message = '';
$addWatchlist_good_message = '';
if ($db_server) {
if (!empty($watchlist_name)) {
$watchlist_name = clean_string($watchlist_name);
$watchlist_description = clean_string($watchlist_description);
mysql_select_db($db_database);
// Insert new Watchlist into Watchlist index
$insert_new_watchlist = "INSERT INTO watchlists (user_id, name, description, category) VALUES ('$user_id', '$watchlist_name', '$watchlist_description', '$watchlist_category')";
mysql_query($insert_new_watchlist) or die("Insert failed. " . mysql_error() . "<br />" . $insert_new_watchlist);
// Select new Watchlist ID
$select_new_watchlist = "SELECT watchlist_id FROM watchlists WHERE name = " . $watchlist_name;
$new_watchlist_id = mysql_query($select_new_watchlist) or die("Insert failed. " . mysql_error() . "<br />" . $select_new_watchlist);
// Add film to new Watchlist
$add_new_film = "INSERT INTO watchlist_films (watchlist_id, film_id) VALUES ('$new_watchlist_id', '$rt_id')";
mysql_query($add_new_film) or die("Insert failed. " . mysql_error() . "<br />" . $add_new_film);
$addWatchlist_good_message = '<div class="alert alert-success">Watchlist created successfully!</div>';?>
<script>
$('a.add-watchlist').trigger('click');
</script><?php
}
} else {
$addWatchlist_bad_message = '<div class="alert alert-error">Error: could not connect to the database.</div.';?>
<script>
$('a.add-watchlist').trigger('click');
</script><?php
}
require_once("db_close.php");
}
My query, however, seems to be failing at the SELECT statement, in between adding the new Watchlist to the Watchlist index and adding the film to the newly created Watchlist.
try this
$query1 = "INSERT INTO watchlist_films (watchlist_id, film_id)
VALUES ('" . $watchlist_name['watchlist_id'] . "', '$rt_id')";
$query2= "INSERT INTO watchlists ('watchlist_id')
VALUES (" . $watchlist_name['watchlist_id'] . ")";
$result = mysqli_multi_query($query1, $query2);
You will need to write an INSERT for each table.
$mysqli->query("INSERT INTO watchlist_films (watchlist_id, film_id)
VALUES ('" . $watchlist_name['watchlist_id'] . "', '$rt_id')");
$mysqli->query("INSERT INTO watchlists ('watchlist_id')
VALUES (" . $watchlist_name['watchlist_id'] . ")");

Categories