How would you order by two columns in MYSQL Database? - php

I have a complex problem that I have been working on for a while. I don't even know if this is possible to do.This is an iOS app where users can reorder rows in the tableview and it updates the database (ordering02) with the temporary indexpath.row.
Columns to order by:
ordering01 : Products are ordered 1..2..3... and so on
ordering02 : When product is moved to a new position (indexPath.row) in the app this temporarily holds the new position in the mysql database until the user saves changes. Once the user saves changes that position is then saved into ordering01.
What I am trying to do is display the unsaved product order in the app (tableView). To do this I will need to sort by both ordering01 & ordering02. The complicated part is that I need the query to check if ordering02 exists. If ordering02 exists then that's the column that is used but if it doesn't exist then the column used is ordering01.
$sql = mysql_query("SELECT * FROM products WHERE status = '1' ORDER BY [Check if ordering 02 exists, if it does use ordering 02 if not use ordering01] ");
while($row = mysql_fetch_array($sql01)){
}
Does this Make sense and is it even possible?

For the temporary storage, why not use arrays, until the user clicks the save, then take from the array and insert into your table.
The best way to merge the two tables, is using the "JOINS" command in your SQL code and checking if the table exists, PHP offers a call method called "exists()", so you would first call the name of the table (ordering02) inside your if statement.
So you get:
$con = mysqli_connect(...);
$tblName = "ordering02";
If (exists($tblName)){
# Perform action
}else{
# table doesn't exist
}

Related

PHP / MYSQL: Creating a query that can search data from 2 columns but can be optional to 2 or 1

based on my question, I have a table named tbl_programme. That table has 3 columns which are ID, session, and class. Now, I want to create an MYSQL query for a PHP website that can display the data based on the 3 columns, which are session, class, and course.
From that 2 columns, it's not compulsory to use them where clause for all 2 columns, it can be two columns or one column only. Below is my current query:
SELECT * from tbl_programme where session = '$session' AND class = '$class';
If I run the query with only put data for class and course, it still does not display the specific data that I want. I try to change the use of OR, but still the same. Can anyone help me to solve this?

save data in mysql by stored procedure

i have a table that must by update every month, due i upload text file on server and save it in temporary table, the bellow code show it:
$result_emp = "LOAD DATA LOCAL INFILE'".$myFile_emp."' INTO TABLE infemptemp COLUMNS TERMINATED BY ','";
then after update successfully and insert new data in "infemptem" table, i should compare the data of main table's "infemp" that have old data by "infemptemp" that have new data, for do this Scenario i write bellow code:
$viwe_emp =mysqli_query($conn,"select * from infempsame where 1");
$NumRows_emp=mysqli_num_rows($viwe_emp);
//echo $NumRows_vam;
$i=0;
while(($row=$viwe_emp->fetch_assoc())!=NULL)
{
$prsid1=$row['PrsID'];
$AccID1=$row['AccID'];
$numid1=$row['NumID'];
$sql2="select * from infempsame where prsID='".$prsid1."';";
if (mysqli_query($conn,$sql2))
{
$sql2_update="UPDATE `infemp` SET AccID='".$AccID1."',NumID='".$numid1."' WHERE prsID='".$prsid1."';";
if(mysqli_query($conn,$sql2_update))
{
$i+=1;
}
}// end if (mysqli_query($conn,$sql2))
}// end while insert new fields of infvam
by attention to the code and have 3500 record in "infempsame " table on my database, when i want update "infemp" table, the time out on browser occur.
I think if write above code by procedure, my problem solved.
Is it true? How do i can write procedure and call or use it?
Best Regards.
A stored procedure would be overkill. There is a better way hidden away but it get's only a very brief mention in the manual
You can also perform UPDATE operations covering multiple tables.
However, you cannot use ORDER BY or LIMIT with a multiple-table
UPDATE. The table_references clause lists the tables involved in the
join. Its syntax is described in Section 13.2.9.2, “JOIN Syntax”. Here
is an example:
UPDATE items,month SET items.price=month.price WHERE
items.id=month.id;
Thus you can write a simple query to get rid of the PHP script like this.
UPDATE infemp, infemptemp
SET infemp.AccID=infemptemp.AccID,
infemp.NumID=infemptemp.numID
WHERE infemp.prsID=infemptemp.prsID;
if you have an index on the prsID column this should complete very quickly.

Dynamic textbox creation with db using ajax/javascript/php

I have two tables. company_details and company_specials. Each company_details can have multiple specials. I display the company details at http://eurothermwindows.com/ed/admin.php
The first row and fourth row that has the 0 in the active column is from company_details and the rows below are from company_specials.
Currently the code allows for dynamic modification of the company_details rows as denoted by the compid in that table. However i would like to have the rows below it to be dynamically modified as well but it's using the same compid and i'm not sure how to separate them in the code.
Code below is the code being generated for the company_specials. I need a way to uniquely identify each row and be able to modify it.
http://pastebin.com/RAe9iwAP
Could somebody provide some guidance please? I'm thinking that i would probably need to uniquely identify each of the specials within the company_specials or set some sort of pointers?
Add unique ids to your db tables and output hidden text fields with each record to indicate it table origin and its id. this will allow the code to know which table had which row updated or deleted. inserting new records can be accomplished by offering a blank record of each type at the end of each group, so there would be one blank specials record at the end of each group and one blank company record at the end of the table.
Put a unique name on each input field of the form name='comp[<?php echo $comp_id?>][<?php echo $comp_field_name?>]' and name='spec[<?php echo $spec_id?>][<?php echo $spec_field_name?>]' so that when the table is posted, PHP will see two arrays, $comp and $spec. You can loop over these with
foreach ($comp as $id=>$row)
{
}
and loop over each $row to build an SQL update or insert statement with
foreach ($row as $fld=>$val)
{
}
Seems you're on the right track. You will indeed need to identify the rows uniquely. You could add a unique id to your company_specials table and use that. Or use some other combination of attributes that's unique to each row in your company_specials table (e.g. concatination of compid & specdate). Whatever fits your information-structure. I would advise to just add a unique id to your specials table.
Be sure to also add that unique-constraint to your database-system to prevent invalid data from being entered.

php mysql - document retrieveal and display

I built a document upload admin screen, where my client can browse and upload pdf documents to a mysql dbase.
I have two separate tables for the Agendas, and one for Minutes. both have separate table names "upload" and "upload_mins".
on the index.php page, I have the page fetch each row of the database, and display all of the valid documents on a "download" page.
I have come a across a problem.
Each dbase is set to increment ID. now that there is two databases, they are coming to utilize the same ID.
so I am pulling from the Agenda table:
http://www.example.com/clerk.php?ID=77
and I am pulling from the Minutes table also:
http://www.example.com/clerk.php?ID=77
and they happen to have the same increment ID.
Is there some way to avoid this? Can I add a field parameter to the minutes to make sure that they don't have the same URL when pulling documents?
Create a integer field, or txt field?
i.e. http://www.example.com/clerk.php?ID=77&min=yes
If these are just documents, you could store them in a single table but have a column called type that differentiates between minutes and agendas. That way, IDs will be unique.
You could also extend the types column be a foreign key to a types table, so you can extend it to include additional document types such as spreadsheets in the future easily.
This would also aid the front-end display, as you would only need one query to fetch the documents within a batch or timeframe, but add them to differing arrays. For example:
// get the last 20 uploaded documents
$sql = "SELECT * FROM documents ORDER BY created DESC LIMIT 0,20";
$res = mysql_query($sql);
while ($doc = mysql_fetch_object($res)) {
$type = $doc->type;
if (!isset($docs[$type]) || !is_array($docs[$type])) {
$docs[$type] = array();
}
$docs[$type][] = $doc;
}
// loop over agendas
foreach ($docs['agendas'] as $agenda) {
echo '' . $agenda->title . '';
}
// loop over minutes
foreach ($docs['minutes'] as $minutes) {
echo '' . $minutes->title . '';
}
...
You say that the problem you are having is with URLs being duplicated. You have 2 different options to solve that.
The first is to create an identifier that tells you which table you want. You could have agenda.php and minutes.php, or you could have clerk.php?ID=77&type=1 and clerk.php?ID=77&type=2.
This will allow you to know which table you are referencing. This is also the approach I would recommend. There is no reason to avoid duplicate keys in different tables as long as you have a way of knowing which table you need.
The second option is to put all your records into a single table. You can then add a type column that specifies what type of document it is. You can then leave your clerk.php file alone, but need to change the upload page to populate the type column.
If you are just storing PDFs in the database, you shouldn't need anything in this table except id, type, and the document itself.

How to sync two database tables with each other in mysql PHP

I have two tables called clients, they are exactly the same but within two different db's. Now the master always needs to update with the secondary one. And all data should always be the same, the script runs once per day. What would be the best to accomplish this.
I had the following solution but I think maybe theres a better way to do this
$sql = "SELECT * FROM client";
$res = mysql_query($conn,$sql);
while($row = mysql_fetch_object($res)){
$sql = "SELECT count(*) FROM clients WHERE id={$row->id}";
$res1 = mysql_query($connSecond,$sql);
if(mysql_num_rows($res1) > 0){
//Update second table
}else{
//Insert into second table
}
}
and then I need a solution to delete all old data in second table thats not in master.
Any advise help would be appreaciated
This is by no means an answer to your php code, but you should take a look # Mysql Triggers, you should be able to create triggers (on updates / inserts / deletes) and have a trigger (like a stored proceedure) update your table.
Going off the description you give, I would create a trigger that would check for changes to the 2ndary table, then write that change to the primary table, and delete that initial entry (if so required) form the 2ndary table.
Triggers are run per conditions that you define.
Hopefully this gives you insight into 'another' way of doing this task.
More references on triggers for mysql:
http://dev.mysql.com/doc/refman/5.0/en/triggers.html
http://www.mysqltutorial.org/create-the-first-trigger-in-mysql.aspx
You can use mysql INSERT ... SELECT like this (but first truncate the target table):
TRUNCATE TABLE database2.client;
INSERT INTO database2.client SELECT * FROM database1.client;
It will be way faster than doing it by PHP.
And to your notice:
As long as the mysql user has been given the right permissions to all databases and tables where data is pulled from or pushed to, this will work. Though the mysql_select_db function selects one database, the mysql statement may reference another if you use complete reference like databasename.tablename
Not exactly answering your question, but how about just using 1 table, instead of 2? You could use a fedarated table to access the other (if it's on a different mysql instance) or reference the table directly (like shamittomar's suggestion)
If both are on the same MySQL instance, you could easily use a view:
CREATE VIEW database2.client SELECT * FROM database1.client;
And that's it! No synchronizing, no cron jobs, no voodoo :)

Categories