473,791 Members | 2,725 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamically generate mySQL queries

Hi All,

Please accept my appologies in advance for what I expect will be a
reasonably simple question.

I have an html form (which is generated in php) which contains a
number of rows (one row per product in the 'products' table).

It is generated with the following php

<code>
// create a table for the results
echo('<table border=1 cellpadding=2>' );
echo('<tr> <th>Product Description</th><th>Sales $</th><th>Sales
Units</th><th>Credits $</th><th>Credits Units</th> </tr>');

// add the results to the table
while ( $row = mysql_fetch_arr ay($result) ) {
// get columns from the output on the current row
$ProdDesc = $row['ProductDescrip tion'];
$ProdID = $row['ID'];
// write content collected above into table cells
echo('<tr><td>' );
echo($ProdDesc) ;
echo('</td><td>');
echo('<form action="update-db.php" method="post">< input type="text"
name="sd');
echo($ProdID);
echo('">');
echo('</td><td>');
echo('<form action="update-db.php" method="post">< input type="text"
name="su');
echo($ProdID);
echo('">');
echo('</td><td>');
echo('<form action="update-db.php" method="post">< input type="text"
name="cd');
echo($ProdID);
echo('">');
echo('</td><td>');
echo('<form action="update-db.php" method="post">< input type="text"
name="cu');
echo($ProdID);
echo('">');
echo('</td></tr>');
}
echo('</table>');
//the table is complete
</code>

The values sd1, su1, cd1, cu1,...... cuXX are all available to the
update-db.php page which is called when this form is submitted so I am
fairly sure this is working correctly.

So far, so good, but when it comes to inserting the data into the
database I have not been able to create the SQL dynamically (in
testing I know the number of products and have manually written lots
of SQL INSERTs but this will not work in the real world)

The SQL needs to look like roughly like this:
mysql_query ("INSERT INTO sales_dollars (SaleID, ProductID,
WeekCommencing, Sales, Credits) VALUES ('',
'$prodID','$Wee kCommencing','$ sd1', '$cd1')");

My logic was to say something like this (which needless to say doesn't
work !)
<?php

for ($prodID = 1; $prodID <= $prodCount; $prodID++)
{
$currentSD = "sd" . $prodID
$currentSU = "su" . $prodID
$currentCD = "cd" . $prodID
$currentCU = "cu" . $prodID
mysql_query ("INSERT INTO sales_dollars (SaleID, ProductID,
WeekCommencing, Sales, Credits) VALUES ('',
'$prodID','$Wee kCommencing','$ currentSD', '$currentCD')") ;
}

I may have messed up the for loop here but the real problem was that
query would insert '$sd1', '$sd2' etc as text strings into the
database rather than evaluating $sd1 to it's value (passed from the
original table which would be a number)

I have tried using eval() with no success (though that may well be due
to my complete newbieness with php). I have also tried passing the
values from the original html as arrays and trying to use simillar
logic as above to read from $array[$currentArrayEl ement] also with no
success. Again, if I manually echo the results of $array[0] I am
returned the value entered in the first html field but I can not
dynamically select the next array element.

I hope I have made sense of the problem without writing unnecessary
garbage.

Many thanks in advance for your assistance.

Dave Nouwens
Sydney, Australia.
Jul 17 '05 #1
3 2111
Dave Nouwens wrote:
I have an html form (which is generated in php) which contains a
number of rows (one row per product in the 'products' table).

It is generated with the following php

<code>
// create a table for the results
echo('<table border=1 cellpadding=2>' );
echo('<tr> <th>Product Description</th><th>Sales $</th><th>Sales
Units</th><th>Credits $</th><th>Credits Units</th> </tr>');

// add the results to the table
while ( $row = mysql_fetch_arr ay($result) ) {
// get columns from the output on the current row
$ProdDesc = $row['ProductDescrip tion'];
$ProdID = $row['ID'];
// write content collected above into table cells
echo('<tr><td>' );
echo($ProdDesc) ;
echo('</td><td>');
echo('<form action="update-db.php" method="post">< input type="text"
name="sd');
echo($ProdID);
echo('">');
echo('</td><td>');
echo('<form action="update-db.php" method="post">< input type="text"
name="su');
echo($ProdID);
echo('">');
echo('</td><td>');
echo('<form action="update-db.php" method="post">< input type="text"
name="cd');
echo($ProdID);
echo('">');
echo('</td><td>');
echo('<form action="update-db.php" method="post">< input type="text"
name="cu');
echo($ProdID);
echo('">');
echo('</td></tr>');
}
echo('</table>');
//the table is complete
</code>
I think your problem is right there, in the HTML.
<form>s do not nest!
If you have several <form>s in your page the posted data is the contents
of just one of them.

I usually do <form>s and <table>s like this:

<form>
<table>
<tr>
<td>...</td>
<td><input ...></td>
</tr>
<tr>
<td>...</td>
<td><input ...></td>
</tr>
</table>
</form>
The values sd1, su1, cd1, cu1,...... cuXX are all available to the
update-db.php page which is called when this form is submitted so I am
fairly sure this is working correctly.
Hmmm ... maybe I'm wrong :)

So far, so good, but when it comes to inserting the data into the
database I have not been able to create the SQL dynamically (in
testing I know the number of products and have manually written lots
of SQL INSERTs but this will not work in the real world)

The SQL needs to look like roughly like this:
mysql_query ("INSERT INTO sales_dollars (SaleID, ProductID,
WeekCommencing, Sales, Credits) VALUES ('',
'$prodID','$Wee kCommencing','$ sd1', '$cd1')");

My logic was to say something like this (which needless to say doesn't
work !)
<?php

for ($prodID = 1; $prodID <= $prodCount; $prodID++)
{
$currentSD = "sd" . $prodID
$currentSU = "su" . $prodID
$currentCD = "cd" . $prodID
$currentCU = "cu" . $prodID
mysql_query ("INSERT INTO sales_dollars (SaleID, ProductID,
WeekCommencing, Sales, Credits) VALUES ('',
'$prodID','$Wee kCommencing','$ currentSD', '$currentCD')") ;
}

I may have messed up the for loop here but the real problem was that
query would insert '$sd1', '$sd2' etc as text strings into the
database rather than evaluating $sd1 to it's value (passed from the
original table which would be a number)
Try variable variables
http://www.php.net/manual/en/languag...s.variable.php

$currentSD = ${'sd' . $prodID};
If you turn register_global s off (which might be a good idea) change
that line to

$currentSD = $_POST['sd' . $prodID];

I have tried using eval() with no success (though that may well be due
to my complete newbieness with php). I have also tried passing the
values from the original html as arrays and trying to use simillar
logic as above to read from $array[$currentArrayEl ement] also with no
success. Again, if I manually echo the results of $array[0] I am
returned the value entered in the first html field but I can not
dynamically select the next array element.


Happy Coding :)

--
USENET would be a better place if everybody read: : mail address :
http://www.catb.org/~esr/faqs/smart-questions.html : is valid for :
http://www.netmeister.org/news/learn2quote2.html : "text/plain" :
http://www.expita.com/nomime.html : to 10K bytes :
Jul 17 '05 #2
Dave Nouwens wrote:
Hi All,

Please accept my appologies in advance for what I expect will be a
reasonably simple question.

I have an html form (which is generated in php) which contains a
number of rows (one row per product in the 'products' table).

It is generated with the following php

<code>
// create a table for the results
echo('<table border=1 cellpadding=2>' );
echo('<tr> <th>Product Description</th><th>Sales $</th><th>Sales
Units</th><th>Credits $</th><th>Credits Units</th> </tr>');

// add the results to the table
while ( $row = mysql_fetch_arr ay($result) ) {
// get columns from the output on the current row
$ProdDesc = $row['ProductDescrip tion'];
$ProdID = $row['ID'];
// write content collected above into table cells
echo('<tr><td>' );
echo($ProdDesc) ;
echo('</td><td>');
echo('<form action="update-db.php" method="post">< input type="text"
name="sd');
echo($ProdID);
echo('">');
echo('</td><td>');
echo('<form action="update-db.php" method="post">< input type="text"
name="su');
echo($ProdID);
echo('">');
echo('</td><td>');
echo('<form action="update-db.php" method="post">< input type="text"
name="cd');
echo($ProdID);
echo('">');
echo('</td><td>');
echo('<form action="update-db.php" method="post">< input type="text"
name="cu');
echo($ProdID);
echo('">');
echo('</td></tr>');
}
echo('</table>');
//the table is complete
</code>

The values sd1, su1, cd1, cu1,...... cuXX are all available to the
update-db.php page which is called when this form is submitted so I am
fairly sure this is working correctly.

So far, so good, but when it comes to inserting the data into the
database I have not been able to create the SQL dynamically (in
testing I know the number of products and have manually written lots
of SQL INSERTs but this will not work in the real world)

The SQL needs to look like roughly like this:
mysql_query ("INSERT INTO sales_dollars (SaleID, ProductID,
WeekCommencing, Sales, Credits) VALUES ('',
'$prodID','$Wee kCommencing','$ sd1', '$cd1')");

My logic was to say something like this (which needless to say doesn't
work !)
<?php

for ($prodID = 1; $prodID <= $prodCount; $prodID++)
{
$currentSD = "sd" . $prodID
$currentSU = "su" . $prodID
$currentCD = "cd" . $prodID
$currentCU = "cu" . $prodID
mysql_query ("INSERT INTO sales_dollars (SaleID, ProductID,
WeekCommencing, Sales, Credits) VALUES ('',
'$prodID','$Wee kCommencing','$ currentSD', '$currentCD')") ;
}

I may have messed up the for loop here but the real problem was that
query would insert '$sd1', '$sd2' etc as text strings into the
database rather than evaluating $sd1 to it's value (passed from the
original table which would be a number)

I have tried using eval() with no success (though that may well be due
to my complete newbieness with php). I have also tried passing the
values from the original html as arrays and trying to use simillar
logic as above to read from $array[$currentArrayEl ement] also with no
success. Again, if I manually echo the results of $array[0] I am
returned the value entered in the first html field but I can not
dynamically select the next array element.

I hope I have made sense of the problem without writing unnecessary
garbage.

Many thanks in advance for your assistance.

Dave Nouwens
Sydney, Australia.


Variable variables can be evaluated thus:

$currentSD = ${"sd".$prodID} ;
$currentSU = ${"su".$prodID} ;
$currentCD = ${"cd".$prodID} ;
$currentCU = ${"cu".$prodID} ;

It may also be a case of evaluating the SQL string before passing to
mysql_query():

$sqlInsert = "INSERT INTO sales_dollars (SaleID, ProductID,
WeekCommencing, Sales, Credits) VALUES ('',
'".$prodID."',' ".$WeekCommenci ng."','".$curre ntSD."', '".$currentCD." ')";

mysql_query($sq lInsert);

Hope this helps.

===
Michael S. Clark
Web Applications Developer
Scotland On Line
Jul 17 '05 #3
"Michael S. Clark" <mc****@scotlan donline.co.uk> wrote in message news:<c9******* ***@phys-pa.scotland.net >...

--8<--8<--8<
Hope this helps.

===
Michael S. Clark
Web Applications Developer
Scotland On Line


It helped tremendously, thankyou (and thanks also to Pedro for getting
it started in the right direction)

Dave
Jul 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2982
by: Jonathan Epstein | last post by:
I have a collection of CSV datasets which will all contain different numbers of columns and different column headers. There will always be a fixed number of such files and they have some common characteristics, especially those with column names in common (e.g., at some point I will be performing some database joins based upon similar column names). Initially I would like to parse each CSV file and automatically create a mySQL table...
4
46966
by: petermichaux | last post by:
Hi, I am interesting in using PHP to dynamically create an XML document and then use XSLT to transform to XHTML. I have come across two methods for doing this. I made two equivalent examples so you can see what I mean. http://members.shaw.ca/petermichaux/store/XML_XSLT_method.html I am interested in critisim of how I implemented each method. However my main problem is deciding between methods. Which method is better for
0
519
by: Plymouth Acclaim | last post by:
Hi guys, We have a problem with Dual AMD64 Opteron/MySQL 4.0.18/Mandrake 10 for a very high volume site. We are evaluating the performance on our new server AMD64 and it seems it's slow compared to Dual Xeon/MySQL 4.0.15/RedHat8 and Dual Xeon/MySQL 4.0.18/Mandrake 10. And it seems there are zombie threads. 570 threads in 1 hour and we didn't even use JDBC connection pooling at all. These threads are supposed to be gone within 60...
11
17578
by: DJJ | last post by:
I am using the MySQL ODBC 3.51 driver to link three relatively small MySQL tables to a Microsoft Access 2003 database. I am finding that the data from the MySQL tables takes a hell of a long time to load making any kind linkage with my Access data virtually useless. I have the MySQL driver setup in as a USER DSN. The MySQL data is sitting out on a server and the Access database is running locally. The network connection is very...
4
5403
by: Jorey Bump | last post by:
I can retrieve today's date: mysql> SELECT CURDATE() AS begin; +------------+ | begin | +------------+ | 2005-06-01 | +------------+ 1 row in set (0.00 sec)
7
2736
by: Daz | last post by:
Hi. I am trying to select data from two separate MySQL tables, where I cannot use join, but when I put the two select queries into a single query, I get an error telling me to check my syntax. Both of the queries work fine when I use them to query the MySQL server directly. My guess is that the MySQL extension only expects a single resource back from the database, but get's several, or that it just checks the statement first, and decides...
13
3426
by: Ciaran | last post by:
Hi All, Is it faster to have mySql look up as much data as possible in one complex query or to have php do all the complex processing and submit lots of simple queries to the mysql database? Cheers, Ciarán
6
38530
Atli
by: Atli | last post by:
This is an easy to digest 12 step guide on basics of using MySQL. It's a great refresher for those who need it and it work's great for first time MySQL users. Anyone should be able to get through this without much trouble. Programming knowledge is not required. Index What is SQL? Why MySQL? Installing MySQL. Using the MySQL command line interface
12
1422
by: Bobby Edward | last post by:
I have an advanced search box. The user can type in multiple words in the box. Those words are then used in the WHERE clause against a Description db field. So these words: plumber carpenter electrician Would essentially equate to: "WHERE (Description LIKE '%plumber%') OR (Description LIKE '%carpenter%') OR (Description LIKE '%electrician%')" Is there any easy way to dynamically create this WHERE clasue? I know how
0
9669
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10154
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9029
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5430
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4109
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2913
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.