Fixing Ambiguous Column in WHERE Clause - javascript

I need to display a table that corresponds to the value chosen after I select a value in a dropdown list. If I run this query in my SQLPro Studio, and obviously without the $mr_id variable, it says that MR_ID is ambiguous. Is there a way to fix this? This seems like a small problem to me but I can't seem to figure it out. I just need to make sure there is a WHERE clause somewhere so that it will only display the values that correlate to the value selected.
The table is only 2 columns, MR_ID (which is what is displayed in the dropdown list and also concatenated with another column not in the table) and Supp_ID.
<?php
$host="xxxxxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxx";
$dbPass="xxxxxxxxxxxxxx";
$mr_id = $_POST['mr_id'];
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql_one = "
SELECT CONCAT(CAST(Stage_Rebate_Index.MR_ID AS INT),' - ', Stage_Rebate_Master.MR_Name) AS MR_ID,
Stage_Rebate_Index.MR_ID AS sort_column,
CAST(Supp_ID as INT) AS Supp_ID
FROM Stage_Rebate_Index
LEFT JOIN Stage_Rebate_Master
ON Stage_Rebate_Master.MR_ID = Stage_Rebate_Index.MR_ID
WHERE Stage_Rebate_Index.MR_ID = '$mr_id'
ORDER BY sort_column";
//$users = $dbh->query($sql);
$users_one = $dbh->query($sql_one);
?>
<html>
<body>
<!-- Table -->
<p>
<div id="table_div">
<table border="1" id="index_table" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header">
<td>MR ID</td>
<td>Supplier ID</td>
</tr>
</thead>
<?php foreach($users_one->fetchAll() as $supp) { ?>
<tr>
<td class="mr_id"><?php echo $supp['MR_ID'];?></td>
<td class="supp_id"><?php echo $supp['Supp_ID'];?></td>
</tr>
<?php } ?>
</table>
</div>
</body>
</html>
EDIT:
Updated query with harcoded value...
$sql_one = "
SELECT
CONCAT(CAST(t1.MR_ID AS INT),' - ', COALESCE(t2.MR_Name, '')) AS MR_ID,
t1.MR_ID AS sort_column,
CAST(Supp_ID as INT) AS Supp_ID
FROM Stage_Rebate_Index t1
LEFT JOIN Stage_Rebate_Master t2
ON t2.MR_ID = t1.MR_ID
WHERE
CONCAT(CAST(t1.MR_ID AS INT),' - ', t2.MR_Name) = LTRIM(RTRIM('1 - Company A'))
ORDER BY sort_column";

In your where clause
WHERE
MR_ID = '$mr_id'
Specify the table you want it from as such:
WHERE
Stage_Rebate_Master.MR_ID = '$mr_id'
You should probably also specify the tables in your select clause too.

From your comment on Zackary Murphy's solution, it sounds like your MR_ID you want in the where is actually the computed value in the select, not the column value on the tables. Try this.
SELECT
CONCAT(CAST(t1.MR_ID AS INT),' - ', COALESCE(t2.MR_Name, '')) AS MR_ID,
t1.MR_ID AS sort_column,
CAST(Supp_ID as INT) AS Supp_ID
FROM Stage_Rebate_Index t1
LEFT JOIN Stage_Rebate_Master t2
ON t2.MR_ID = t1.MR_ID
WHERE
CONCAT(CAST(t1.MR_ID AS INT),' - ', t2.MR_Name) = LTRIM(RTRIM('$mr_id'))
ORDER BY sort_column
*Edit to add table aliases.
*Edit Added white space trim.
*Edit added COALESCE in case t2.MR_Name is null.

You have to give fully qualified name of table columns.
Like you have 2 tables, table1 and table2, and have col1 as column name in both table
If you are retrieving data from these 2 table below is query example
select
table1.co11 as tbl1col1, table2.col1 as tbl2col1
from
table1
join
table2 on table1.id = table2.id
where
table1.col1 = "your statement" and table2.col1 = "your statement"

Related

sending html data to view and then sending to controller to update sql database

I have a HTML table where one of the columns value is dynamically added. I have an update button, upon clicking it I want this data to get updated in my sql database. For this, I am planning to first fetch the table data and put into view , then send data to controller and then updating sql.
I am stuck at the first step,
Descibing table below
<thead>
<tr>
<th>ID</th>
<th >Name</th>
<th>Active</th>
<th>Order By</th>
</tr>
</thead>
<tbody>
#if (ViewBag.data != null)
{
foreach (var item in ViewBag.data)
{
<tr>
<td >#item.AutoID</td>
<td #item.Text</td>
<td >#item.Active</td>
<td>#item.OrderBy</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
<input type="submit" value="Update Preference" class="BtnUpdOrderId" />
</div>
I tried this below js function to fetch the data
$(".BtnUpdOrderId").click(function () {
var tr = $(this).closest('tr');
var id = tr.find('input[name="autoid"]').val();
var text = tr.find('input[name="text"]').val();
var active = tr.find('input[name="active"]').val();
var orderby = tr.find('input[name="orderby"]').val();
alert('type1 : ' + id + ' ' + text + ' ' + active + ' ' + active);
});
but not sure why nothing came in alert
var TableData = new Array();
$('#tblLookup1 tr').each(function (row, tr) {
TableData = TableData + $(tr).find('td:eq(0)').text();
alert(TableData);
});
then tried the above block of code to get data in a variable but still not able to get anything.
Once I get the data I can try sending from view->controller.
So need the following help:
what mistake am I making?
once this is fixed, how to send data to sql? (this is a ado.net based mvc project)
you might want to consider creating a json object:
Creating json object in mvc and returning from controller
then build your table Convert JSON array to an HTML table in jQuery
finally, the update need only post back the json object
https://dontpaniclabs.com/blog/post/2013/02/27/posting-json-data-to-an-mvc-controller-via-ajax/
if you going to use this jason object make sure you use serialization
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-6-0
your have to patch these concepts together but there are a lots of tutorials and examples online so it be a good learning experience
I hope this helps
helpful links:
https://www.sqlshack.com/modifying-json-data-using-json_modify-in-sql-server/
Updating a JSON object using Javascript
https://www.geeksforgeeks.org/how-to-convert-json-data-to-a-html-table-using-javascript-jquery/
create json object from html table using selected colums using jquery

How to move HTML table elements up or down by using JavaScript and keep the order of all elements intact (i.e. 1,2,3...etc) in the front end?

I have HTML table with several elements (td tags), each row has 4 buttons, "Edit", "Delete", "Move Up" and "Move Down". The "Move Up" and "Move Down" buttons behave oddly sometimes as their actions can cause several rows to have the same "item_order" in the MySQL database. Thus, when trying to move other rows up or down, the functions won't work as intended because of the duplicate "item_order" for more than one row. When checking the database I can see many rows have "item_order = 1" or 2 or 5 and so on
I would like the "Move Up" and "Move Down" buttons to keep updating the MySQL DB (but hopefully in a proper ordering), AND ALSO to move the rows in the UI front-end so that they appear in the desired order 1,2,3 ...etc
Please be patient with me because I am a newbie in the software development business and I am still learning things.
Below is the table:
<tr id="tr_<%=String.valueOf(RowCount)%>" onmouseover="showRow(<%=String.valueOf(RowCount)%>)" onmouseout="hideRow(<%=String.valueOf(RowCount)%>)">
<td valign="top" width="200px" class="tablepad tableborder_bottom">(<%=String.valueOf(RowCount)%>) <%=topic%></td>
<td valign="top" width="200px" class="tableborder_left"><%=sub_topic%></td>
<td valign="top" width="280px" class="tableborder_left"><%=item%></td>
<td valign="top" class="tableborder_left"><img src="./media/images/edit.jpeg" border="0"/></td>
<td valign="top" class="tableborder_bottom"><img src="./media/images/delete.jpeg" border="0"/></td>
<td valign="top" class="tableborder_bottom"><img src="./media/images/16_arrow_up.png" border="0"/></td>
<td valign="top" class="tableborder_bottom"><img src="./media/images/16_arrow_down.png" border="0"/></td>
</tr>
Here is the Java code to update the MySQL Database when "move_up" or "move_down" button is used:
if (action.equals("move_up")){
action="add";
if (whichOrder != 1){
int CurrentOrder = whichOrder;
int NewOrder = whichOrder - 1;
String sqlString1 = "UPDATE msr_summary_notices set item_order = "+String.valueOf(NewOrder)+" WHERE item_order = "+String.valueOf(CurrentOrder);
String sqlString2 = "UPDATE msr_summary_notices set item_order = "+String.valueOf(CurrentOrder)+" WHERE item_order = "+String.valueOf(NewOrder)+" AND absid <>"+rowid;
statement1 = conn.prepareStatement(sqlString1);
int RowsAffected1 = (statement1.executeUpdate());
statement1.close();
statement2 = conn.prepareStatement(sqlString2);
int RowsAffected2 = (statement2.executeUpdate());
statement2.close();
}else{
// Do nothing coz you can move up above 1
}
}
if (action.equals("move_down")){
action="add";
if (whichOrder != MaxValue){
int CurrentOrder = whichOrder;
int NewOrder = whichOrder + 1;
String sqlString1 = "UPDATE msr_summary_notices set item_order = "+String.valueOf(NewOrder)+" WHERE item_order = "+String.valueOf(CurrentOrder);
String sqlString2 = "UPDATE msr_summary_notices set item_order = "+String.valueOf(CurrentOrder)+" WHERE item_order = "+String.valueOf(NewOrder)+" AND absid <>"+rowid;
statement1 = conn.prepareStatement(sqlString1);
int RowsAffected1 = (statement1.executeUpdate());
statement1.close();
statement2 = conn.prepareStatement(sqlString2);
int RowsAffected2 = (statement2.executeUpdate());
statement2.close();
}else{
// Do nothing coz you can move down below MaxValue
}
}
Finally, here is the JavaScript function that shows/hide the rows on mouseout and the functionality to print out the rows:
<script type="text/javascript">
function showRow(RowId){
var Row = document.getElementById("tr_"+RowId);
Row.style.backgroundColor="#CCCCFF";
//console.debug(Row);
}
function hideRow(RowId){
var Row = document.getElementById("tr_"+RowId);
Row.style.backgroundColor="#FFFFFF";
}
if ((action.equals("move_up"))||(action.equals("move_down"))){
out.println("showRow("+rowid+")");
//console.log(RowId);
}
</script>
</head>
I did a lot of research and I think the problem can be in the session that could be badly handled. Also, if the "item_order" in the DB remains messy (same item_order for multiple rows) I am not too bothered about it, as the main expected result is for the User Interface to show proper order of the rows.

PHP/SQL Dynamic menu depending on different tables

I'm trying to manage a dynamic menu based on results from tables in my database.
Code below is so far i have come.. But i can't get it to display as i want to.
i have 3 tables in my database looking like this.
ws_categories
id
maincat (name of main-category)
ws_subcategories
id
subcat (Name of sub-category)
parentcat (id of main-category)
ws_subsubs
id
subsub (Name of 2nd-sub-category)
parentsub (id of sub-category)
What i want to achieve?
Having a simple vertical menu, that outputs main categories, and onclick, submenue alternatives related to that main category will show, if a sub category has a 3rd submenu/submenues, they will show under..
Code below is so far i have come.. But i don't seem to understand why it output main category several times and not just once..
To be clear, i do not understand how i should use join to achieve this. I want to be able to echo all main categories once, and subcategories once, and if there is one or more 2nd sub categories i want them to echo too.. How do i achieve this with join? is it even possible or am i looking the wrong way?
Thanks in advance.
PHP
<?php
echo '<div class="dl_parent">';
$results = mysqli_query($link, "SELECT * FROM `ws_categories` INNER JOIN `ws_subcategories` ON `ws_categories`.`id` = `ws_subcategories`.`parentcat`;") or die (mysqli_error($link));
while($row = mysqli_fetch_array($results)){
echo '
<div class="dl_parent">
<div class="dl_link">'.$row['maincat'].'</div>
<div class="dl_sub_dd">
<ul>
<li>'.$row['subcat'].'</li>
</ul>
</div>
</div>
';
}
?>
Javascript
$(window).on('load',function(){
//CLICK-HANDLERS=============================
$('.dl_link').click(function(){
var submenu = $(this).parent().children('.dl_sub_dd');
if (submenu.css('display') == 'none') {
$('.dl_sub_dd').hide(); //first hide any previously showing submenu's
submenu.show(); //then show the current submenu
} else {
submenu.hide(); //hide the current submenu again
}
});
});
CSS
/*LINK------------------------*/
.dl_link {
cursor:pointer;
}
/*DROPMENU--------------------*/
.dl_sub_dd {
display:none;
}
Your SQL request will give you for each main category as many rows as it has sub categories:
row 1: maincat1 | subcat1
row 2: maincat1 | subcat2
etc...
You could make a request to select all maincats, and for each maincat, make another request to select all its subcats. Something like this:
PHP
<?php
$results = mysqli_query($link, "SELECT * FROM `ws_categories`;") or die (mysqli_error($link));
while($row = mysqli_fetch_array($results)){
echo '
<div class="dl_parent">
<div class="dl_link">'.$row['maincat'].'</div>
<div class="dl_sub_dd">
<ul>';
$query = mysqli_query($link, "SELECT * FROM `ws_categories` INNER JOIN `ws_subcategories` ON `ws_categories`.`id` = `ws_subcategories`.`parentcat` WHERE `ws_categories`.`id` = " . $row['id'] . ";") or die (mysqli_error($link));
while($row2 = mysqli_fetch_array($query)) {
echo '<li>'.$row2['subcat'].'</li>';
}
echo '</ul>
</div>
</div>
';
}
?>

Sending and deleting records to database with a drag and drop table

I have three db tables.
-Paid
-Partially Paid
-Owes
When someone registers for an account I send their user_id, name, etc to my 'Owes' db table and then output their name into a drag and drop table I have in the 'Owes' column. As of now if I move anyone's name to any other category (Paid/Partially paid) I am not sure how to delete that record from the Owes db and insert the name into the new db table so the changes are permanent.
What's really throwing me off is how to do it with the drag and drop table. I'm not sure how to apply the logic that when something is dropped into that column that the past record is deleted and a new one is added to that specific table or how to make the changes without a submit button or page reload.
What is a way I can do this and how could I structure it?
PHP
<?php
//Payment Section
$con = mysqli_connect("localhost", "root", "", "db");
$paid_run = mysqli_query($con,"SELECT * FROM paid ORDER BY id DESC");
$partially_paid_run = mysqli_query($con,"SELECT * FROM partial_payment ORDER BY id DESC");
$owes_run = mysqli_query($con,"SELECT * FROM owes ORDER BY id DESC");
$paid_numrows = mysqli_num_rows($paid_run);
$partially_paid_numrows = mysqli_num_rows($partially_paid_run);
$owes_numrows = mysqli_num_rows($owes_run);
if($paid_numrows > 0){
while($row = mysqli_fetch_assoc($paid_run)){
$paid_id = $row['user_id'];
$paid_name = $row['name'];
}
}
if($partially_paid_numrows > 0){
while($row = mysqli_fetch_assoc($partially_paid_run)){
$partially_paid_id = $row['user_id'];
$partially_paid_name = $row['name'];
$partially_paid_amount = $row['payment'];
}
}
if($owes_numrows > 0){
while($row = mysqli_fetch_assoc($owes_run)){
$owes_id = $row['user_id'];
$owes_name = $row['name'];
}
}
?>
$(function() {
$( "#paid, #partially_paid, #owes" ).sortable({
connectWith: ".tdPayment",
remove: function(e, ui) {
var $this = $(this);
var childs = $this.find('div');
if (childs.length === 0) {
$this.text("Nothing");
}
},
receive: function(e, ui) {
$(this).contents().filter(function() {
return this.nodeType == 3; //Node.TEXT_NODE
}).remove();
},
}).disableSelection();
});
Table
<table class="paymentTable" id="dragTable">
<tr>
<th class="thPayment">Paid</th>
<th class="thPayment">Partially Paid</th>
<th class="thPayment">Owes</th>
</tr>
<tr>
<td class="tdPayment" id="paid">
<div>
<?php
if ($paid_name == true) {
echo $paid_name;
} else {
echo "No one has paid";
}
?>
</div>
</td>
<td class="tdPayment" id="partially_paid">
<div>
<?php
if ($partially_paid__name == true) {
echo $partially_paid__name . " - " . $partially_paid_amount;
} else {
echo "No one has made a partial payment";
}
?>
</div>
</td>
<td class="tdPayment" id="owes">
<div>
<?php
if ($owes_name == true) {
echo $owes_name;
} else {
echo "Everyone has paid something";
}
?>
</div>
</td>
</tr>
</table>
Here's a rough outline on how to do it. I would recommend using jQuery, a JavaScript library that has a lot of useful stuff for this.
Implement the drag and drop part using jQuery draggable and droppable. A nice guide can be found here.
Write a PHP page that updates the database the way you want it.
Use jQuery to call that page when something is dropped. This can be done using Ajax.
Clarification of part 3
I recommend looking at the photo manager in the droppable documentation to get a full working example of something similar.
For this to work, you need to set up the HTML so it has some class names and some data attributes:
<h1>Owes</h1>
<div class="bin" data-bin-id="1">
<div class="user" data-user-id="5">Eva</a>
<div class="user" data-user-id="8">Anna</a>
</div>
<h1>Partially paid</h1>
<div class="bin" data-bin-id="2">
<div class="user" data-user-id="2">Tom</a>
...
</div>
...
Then we need to implement some javascript that takes care of calling the PHP when the user drops something:
jQuery(".bin").droppable({
accept: ".user",
drop: function( event, ui ) {
//Get the ID of the bin the user was dropped into.
var intBinID = jQuery(this).attr("data-bin-id");
//Get the ID of the user that was dropped.
var intUserID = ui.droppable.attr("data-user-id");
//Make an ajax call to the PHP page.
jQuery.ajax("update.php?binid=" + intBinID + "&userid=" + intUserID);
}
});
In addition you might want update.php to return something to let the JavaScript know if it worked or not, and if it failed abort the drop.
Disclaimar: Since I don't have all the parts of this project set up, I have not tested this code.
An easier way to do this, is by creating an independent User table where you keep all the users. Then, in a separate table like the ones you have already, you just keep the Id of that user (and maybe some information related to how much he owes or has already payed).
This way, when you have to insert or to update any information about the state of the user, you just have to insert/delete the Id of the User from these tables.
The information about the user will always be safe and kept in it's own table.

Hide <TR> tag based on Recordset NULL value

I am using a Microsoft SQL Server 2005 stored procedure to post records in an HTML table. In the HTML table, I have rows for the following fields: entry #, open date, description, and owner.
Sometimes, the owner field in the db table will be NULL. When this happens, I have ASP response.write "N/A" in the HTML table row corresponding to the owner. However, I'd like to avoid this, as it seems superfluous. Instead, I'm hoping there is a way to just eliminate that table row altoegether if the owner field is NULL in the db. How would I go about doing this? I'm using Javascript, classic ASP, and SQL Server 2005. My code is below. Note - I am a total newbie at all of this. Thanks.
'Declare Variables
Dim CN, RS, vOutputType, vSQL, vNumber, vOwner
'Connection from includes file
Set CN = GetDataConnection
vOutputType = Request.QueryString("ot")
If Request.QueryString("txtNumber") <> "" Then
vNumber = Rtrim(Request.QueryString("txtNumber"))
End If
If Request.QueryString("cboOwner") <> "" Then
vOwner = Rtrim(Request.QueryString("cboOwner"))
End If
If vNumber <> "" Or vOwner <> "" Then
vSQL = "spReport "
vSQL = vSQL & "#vNumber = '" & vNumber & "', "
vSQL = vSQL & "#vOwner = '" & vOwner & "'"
Set RS = CN.Execute(vSQL)
If IsObject(RS) Then
If Not RS.EOF Then%>
<table class="WebApps">
<tr>
<td width="5%"><h3>Entry #</h3></td>
<td width="5%"><h3>Open Date</h3></td>
<td width="5%"><h3>Description</h3></td>
<td width="5%"><h3>Owner</h3></td>
</tr>
<%RS.MoveFirst
Do While Not RS.EOF
%>
<tr>
<td><p><%= RS("ID")%></p></td>
<td><p><%= RS("OpenDate")%></p></td>
<td><p><%= RS("Description")%></p></td>
<td><p><%If (RS("OwnerName")) <> "" Then Response.Write(RS("OwnerName")) Else Response.Write("N/A")%></p></td>
</tr>
<%RS.MoveNext
Loop%>
</table>
<%End If
End If
'Close objects
Set RS = NOTHING
CN.Close
Set CN = Nothing
Since you're a "total newbie" here are some othe pieces of advice.
SQL Injection Attack
Your code:-
vSQL = "spReport "
vSQL = vSQL & "#vNumber = '" & vNumber & "', "
vSQL = vSQL & "#vOwner = '" & vOwner & "'"
Set RS = CN.Execute(vSQL)
DO NOT do this. Someone can create a query string to execute arbitary SQL on your server:-
?txtNumber=30&cboOwner='; arbitary SQL code here ; --
You should always use an ADODB.Command object to execute SQL that requires parameter value retrieved from the client. Web Search "SQL Injection ASP"
The meaning of NULL
You seem a little confused about the meaning of NULL. "the owner field in the db table will be NULL" yet your code is testing for <> "". Null is not the same as empty string. A field that is actually NULL will not be equal to "".
Use Server.HTMLEncode
Your code:-
<td><p><%= RS("Description")%></p></td>
What happens if the Description field contains a < or & character? Worse yet if the data in Description field orignates from data entry on web clients it could contain Javascript injection attempts. Always use Server.HTMLEncode on string data being sent to the client:-
<td><p><%= Server.HTMLEncode(RS("Description"))%></p></td>
Your actual question
Don't be tempted to use VBScript in your ASP page to do the job that SQL should be doing.
Modifiy your SQL with a WHERE clause:-
WHERE Owner IS NOT NULL
or if you're not sure whether Owner will NULL or an empty string:-
WHERE Owner IS NOT NULL AND Owner <> ""
It's best to filter out rows containing NULL values in the SQL query itself, but if you can't for some reason, just move your IF statement up a bit so if the condition isn't met, no table row is written out in the first place:
<%If (RS("OwnerName"))<>"" Then Response.Write( "<tr><td>" & "</td></tr>" ) %>
Filtering the source is of course better, by simply selecting records where OwnerName is not ""
Otherwise you can use your bit of code and modify it slightly
from:
<%RS.MoveFirst
Do While Not RS.EOF
%>
<tr>
<td><p><%= RS("ID")%></p></td>
<td><p><%= RS("OpenDate")%></p></td>
<td><p><%= RS("Description")%></p></td>
<td><p><%If (RS("OwnerName")) <> "" Then Response.Write(RS("OwnerName")) Else Response.Write("N/A")%></p></td>
</tr>
<%RS.MoveNext
Loop%>
to
<%RS.MoveFirst
Do While Not RS.EOF
If (RS("OwnerName") <> "") Then
%>
<tr>
<td><p><%= RS("ID")%></p></td>
<td><p><%= RS("OpenDate")%></p></td>
<td><p><%= RS("Description")%></p></td>
<td><p><%= RS("OwnerName")%></p></td>
</tr>
<%
End If
RS.MoveNext
Loop%>
Haven't tested the code but it should help out.
You can do it in 2 ways.
1) Frontend: Check for NULL values in Owner field as following.
If Not (IsNull(rsNew("Owner")) Then
<table class="WebApps">
...........
End If
2) Backend:
Filter NULL values in your stored procedure using WHERE clause.

Categories

Resources