PHP + HTML: create a form dynamically - php

I'm trying to creat a form dynamically depending on the number of rows of a table in a database. I tried this and it's nor working:
require_once('mysqli_connect.php');
//I select the colum w_spanish from the table selected by the user
$q="SELECT w_spanish FROM ".$_GET['name'];
$r=#mysqli_query($dbc, $q);
echo '<FORM METHOD="POST" ACTION="Correction.php">';
echo '<TABLE BORDER="1">';
//Here is where I generate dinamically a table that can be filled by user
while ($row=mysqli_fetch_array($r, MYSQLI_ASSOC)){
$aux=$row['w_spanish'];
echo '<TR><TD>'.$aux.'</TD><TD><INPUT TYPE="TEXT" NAME="Sol_'.$aux.'" SIZE="20"></TD></TR>';
}
echo '</TABLE>';
echo '<P><INPUT TYPE="SUBMIT" VALUE="Submit" ></P></FORM>';
mysqli_close($dbc);
So when I press submit, the information is not sent to "Correction.php", and I think it's because I creating the HTML form inside php code. How could I do it right??

First off - remove the # from the #mysqli statement as it is masking any errors that maybe happening.
Secondly take the generated code and paste it into http://validator.w3.org/#validate_by_input and see if there are any HTML errors and adjust where necessary.
Thirdly, since the user can select which table to read then your data needs to be super-sanitised as you certainly don't want sql injection attacks here.

The problem may be the query you are running. Without knowing more information, my guess would be your query isn't getting anything. Try dumping the row in each iteration and see what spits out. You may be looking for something like:
$q="SELECT w_spanish FROM tableName WHERE name = " . $_GET['name'];
If that's not it, it could also be the fact that since you are only grabbing one column from the database, you don't need access the information with $aux=$row['w_spanish'];. You can just use:
$aux=$row;
That I'm not 100% on though. Try dumping each row with var_dump() and see what pops out.

First declare $row, then use a do-while loop.
$row = mysqli_fetch_array($r, MYSQLI_ASSOC) do{
$aux=$row['w_spanish'];
echo '<TR><TD>'.$aux.'</TD><TD><INPUT> TYPE="TEXT"NAME="Sol_'.$aux.'" SIZE="20"></TD></TR>';
}while ($row=mysqli_fetch_array($r, MYSQLI_ASSOC))

Related

Why the DB data value is blank for fetch_both in php

In my project, I have some problem in DB
With FETCH_NUM method, it works OK, the content code is:
$nodeName=$_POST['nodeInfo'];
include("DB.php");
$data=array();
$sql="select * from GGtable where node='$nodeName';";
$sR=$conn->query($sql);
$rN=$sR->fetch(PDO::FETCH_NUM);
//while($rowSV=$sR->fetch(PDO::FETCH_BOTH)){
// $data[]=$rowSV;
//}
echo '
<table>
<tr><td>'.$rN[0].'</td></tr>
</table>
'
But when i try fetch_both method, it works fail. the code is:
$nodeName=$_POST['nodeInfo'];
include("DB.php");
$data=array();
$sql="select * from GGtable where node='$nodeName';";
$sR=$conn->query($sql);
while($rowSV=$sR->fetch(PDO::FETCH_BOTH)){
$data[]=$rowSV;
}
echo '
<table>
<tr><td>'.$data["node"].'</td></tr>
</table>
'
$data["node"] is blank, nothing.
it seems nothing wrong, who can help me ?
Your problem is that with this statement:
$data[]=$rowSV;
you are creating an array of arrays. Thus to access the value of the node column, you actually need to use
<tr><td>'.$data[0]["node"].'</td></tr>
or replace 0 with whichever row of data you wish to access.
If you only have one row, just replace $data[]=$rowSV; with $data=$rowSV; and your existing output code will work fine.

php mysql issue with check if record exist before insert

I'm having a little problem with the codes given below. When I'm using the name="staff_number[]" then it insert the record with everything ok even if it is already in the database table and when i use name="staff_number" it does check the record and also give me alert box but when insert the record if it is not in the database it stores only the first number of the staff number like the staff no is 12345 it stores only 1. can anyone help in this record i think there is only a minor issue what I'm not able to sort out.
PHP Code:
<select placeholder='Select' style="width:912px;" name="staff_number[]" multiple />
<?php
$query="SELECT * FROM staff";
$resulti=mysql_query($query);
while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['staff_no']?>"><?php echo $row['staff_name']?></option>
<?php } ?>
</select>
Mysql Code:
$prtCheck = $_POST['staff_number'];
$resultsa = mysql_query("SELECT * FROM staff where staff_no ='$prtCheck' ");
$num_rows = mysql_num_rows($resultsa);
if ($num_rows > 0) {
echo "<script>alert('Staff No $prtCheck Has Already Been Declared As CDP');</script>";
$msg=urlencode("Selected Staff ".$_POST['st_nona']." Already Been Declared As CDP");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Insert Query
$st_nonas = $_POST['st_nona'];
$t_result = $_POST['st_date'];
$p_result = $_POST['remarks'];
$arrayResult = explode(',', $t_result[0]);
$prrayResult = explode(',', $p_result[0]); $arrayStnona = $st_nonas;
$countStnona = count($arrayStnona);
for ($i = 0; $i < $countStnona; $i++) {
$_stnona = $arrayStnona[$i];
$_result = $arrayResult[$i];
$_presult = $prrayResult[$i];
mysql_query("INSERT INTO staff(st_no,date,remarks)
VALUES ('".$_stnona."', '".$_result."', '".$_presult."')");
$msg=urlencode("CDP Staff Has Been Added Successfully");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Your $_POST['staff_number'] is actually an array.
So you have to access it like $_POST['staff_number'][0] here, 0 is a index number.
If the name of select is staff_number[] then $prtCheck will be a array so your check query must be in a loop to make sure your check condition.
if the name is staff_number then the below code is fine.
The answer of amit is right but I will complete it.
Your HTML form give to your PHP an array due to the use of staff_number[] with [] that it seems legit with the "multiple" attribute.
So you have to loop on the given values, you do it with a for and a lot of useless variables without really checking it. From a long time, we have the FOREACH loop structure.
I could help you more if i know what is the 'st_nona', st_date' and 'remarks' values.
According to your question you are getting difficulty in storing the data. This question is related to $_POST array.
Like your question we have selected following ids from the select : 1,2,3,4
It is only storing 1.
This is due to you have not used the loop when inserting the data.
Like below:
<?php
foreach($_POST['staffnumber'] as $staffnumber){
$query=mysql_query("select * from staff where staff_number =".$staffnumber);
if(mysql_num_rows($query)>0){
//action you want to perform
}else{
//action you want to perform like entering records etc. as your wish
}
}
?>
And I would like to suggest you that use the unique keys in database for field and use PHP PDO for database, as it is secure and best for OOPs.
Let me know if you have any queries.

column of table cells text to links

I'm creating a table dynamically from a mysql database that gets fields name, email, city. The email column has emails that I'd like to have as "mailto:" links. Currently they display the email without the hyperlink. There's a 'filter' form on the page as well that when submitted will display only results that correspond with a name specified in the form textbox by the user.
I'm very novice at creating anything dynamic. What's the easiest way to display the email column as hyperlinks? I was thinking about using javascript to do a getElementByID loop for the second td of every tr and amend a "mailto:" the beginning using string manipulation. Maybe this is more practically done in PHP instead?
edit:
I realized the obvious solution to my question. I simply concatenated the a href mailto: before the echo of the php command that gets my email field from the sql db and displays it in the table.
This is, indeed, more practically done in PHP. You can use something like the following, assuming that $result contains the result of a MySQL SELECT statement which fetches the users.
while ($u = $result->fetch_assoc()) {
// Output other data
// ...
echo '' . $u['email'] . '';
// ...
}
If you're still using mysql instead of mysqli (which you shouldn't really be doing), then replace
while ($u = $result->fetch_assoc()) {
with
while ($u = mysql_fetch_assoc($result)) {
$db = new PDO(//your dsn, host and password);
$query = $db->prepare('SELECT name,email from users');
$query->execute(); while($row = $query->fetch(PDO::FETCH_ASSOC))
{
echo ''.$row['name'].'';
}

Using PHP to add a field in MySQL if it doesn' texist

I have a submission script that I wrote in PHP. It is used by multiple surveys at our organization. The surveys are created by other users. When they submit to the script, PHP puts the data into the appropriate table in MySQL. The error that I run into sometimes is that the user(s) update the form. They add a field, or rename an input and the script doesn't account for it since it expects everything to be the same. So, I am trying to find a way to make it accomodate for when a new field is added. Here is what I have:
if( mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$survey."'"))){
echo "table exists";
$sql = "SELECT * FROM " . $survey . ";";
$result = mysql_query($sql)
or die(mysql_error());
$i=0;
while($row = mysql_fetch_row($result));{
echo $row[0];
foreach($_POST as $k => $v){
$i++;
if($k != $row[$i]){
$query = "ALTER TABLE " . $survey . " ADD " . $k . " VARCHAR(100);";
mysql_query($query)
or die(mysql_error());
}
}
}
}
I am used to doing while loops in JS, so I don't know if using i works here (actually, I know it doesn't work... because it doesn't work...). What I am trying to say is that if a key doesn't match a current field name, then add it to the table. How can I return $row correctly?
When I submit to the script it says:
Duplicate column name 'V4'
I have echo $row[0] but it returns a 1. Which is the is the int used in the primary key for the for the first record.
You have a ; at the end of your while loop declaration that shouldn't be there. Not sure if that is causing the problem as you don't say what the above code does do. Update the question if the ; is not the issue.
Your while loop declaration should look like this: while($row = mysql_fetch_row($result)) {
Also, as Marc B so diplomatically put it in a comment to your question, you should be escaping any user input that goes directly into a query.
The easiest way to do this is to use $survey = mysql_real_escape_string($survey), before your first use of $survey, as a start or switch to PDO/MySQLi and use input binding (prepared statements). Here are the prepared statements docs for PDO. More can, and should, be done to protect yourself, but the above is a good start.

How to use Php inside Php?

Can someone tell/show me how to use PHP inside PHP.
I'm trying to make the URL of an image change depending on what value is in a MySQL database.
Here's an example of what I'm trying to do. Bear in mind that $idx already has a value from the URL of the page.
<?php
$query = "SELECT * FROM comment WHERE uname='$idx'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "<img src='' name='comm' width='75px' height='60px' id='mainimage' />";
}
?>
How would I make the source value, for the image, come from a different table?
You can join data from multiple tables in a single SQL query. See: http://www.w3schools.com/sql/sql_join.asp
Example:
SELECT column_name(s)
FROM table_name1
JOIN table_name2
ON table_name1.column_name=table_name2.column_name
You'd do another SQL query inside the while loop. I like how you put it, "Php inside Php", that's pretty much what you do.
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$image_query = "SELECT image_url FROM your_table";
$image_result = mysql_query($image_query);
$image = mysql_fetch_assoc($image_result);
echo "<img src='" . $image['image_url'] . "' name='comm' width='75px' height='60px' id='mainimage' />";
}
Make sure the variable names for your query and result are different from your original query, because you're still using the $result variable from the original query each iteration of the loop. So here I've prefixed them with "image_".
Assuming at a random guess that the other table might be called accounts, and uname is its primary key, you can do a JOIN to grab the data from the both tables in one go. If you can fit what you want to do in a single query that's typically much faster than doing an extra query per row
<?php
$result = mysql_query(
"SELECT comment.*, account.url AS imgurl ".
"FROM comment JOIN account ON comment.uname=account.uname ".
"WHERE comment.uname='".mysql_real_escape_string($idx)."'"
);
?>
<?php while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { ?>
<img src="<?php echo htmlspecialchars($row['imgurl']) ?>" alt="" class="mainimage" />
<?php } ?>
Notes:
you need to escape text you insert into an SQL query, or you've get serious security problems. Use mysql_real_escape_string, or let parameterised queries handle it;
similarly when putting text into an HTML string, htmlspecialchars is needed or you've got other (less serious, but still not good) security issues;
you mustn't use the same id on an element more than once (which it will be, in a loop). The same goes for name on <img>, although there's little reason you'd really ever want to use img name;
width="75px" won't work in an attribute as px-unit measurements are CSS not HTML. Omit the unit, or, better, set a rule in CSS (.mainimage { width: 75px; height: 60px; }) to do them all at once.
How would I make the source value, for the image, come from a different table?
You have to simply ask the different table. You can ask by creating subquery (or join) or create second query inside loop.

Categories