I have an issue where i have a textarea in a form where users can enter names on seperate lines. On submit I explode the "\n".
I then want to pass the values from the array into an Select statement, but when i run the script it only returns one result (the last one) from the array..
here is the code below.
echo "<h1> You searched for the following names </h1>";
include 'conn.php';
mysql_select_db("email_finder", $con);
$Email = $_POST['EmailBox'];
$str = $Email;
$lines = explode("\n", $str);
//$in = implode(',', $lines);
//$userStr = implode(',', $lines);
echo "<table border='0'>
<tr>
<th style='color:White' width='180px'; bgcolor=#999999>Name</th>
<th style='color:White' width='250px'; bgcolor=#999999>Email</th>
</tr>";
echo "<pre>";
print_r($lines);
echo "</pre>";
foreach($lines as $array_element) {
$result = mysql_query("SELECT * FROM `emails` WHERE `Name` IN('$array_element') ORDER BY `LastName`");
echo "<pre>";
print_r($array_element);
echo "</pre>";
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
echo "<tr>";
echo "<td style='padding-left:5px'><b> ".$row['Name']."</b> : </td>";
printf("<td style='padding-left:5px'>" .$row['Email']. "</td>");
echo "</tr>";
echo "<pre>";
print_r($row);
echo "</pre>";
}
}
echo "</table><br />";
echo "Email <b>ALL</b> these Students: <a href=mailto:".$row['Email']." >Click Here</a> <br />";
mysql_close($con);
echo '<br />';
If you can help i would be greatful
Thanks
Try using equals instead of IN:
$result = mysql_query("SELECT * FROM emails WHERE Name='$array_element' ORDER BY LastName");
Otherwise my advise to debug it would be to put an exit(); statement on your first pass of the while loop to check your array value and/or if you get a result of the first entry. something like:
foreach($lines as $array_element) {
$result = mysql_query("SELECT * FROM `emails` WHERE `Name`='$array_element' ORDER BY `LastName`");
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
print_r($row);
exit;
...
Guessing you've got OS specific line endings tripping you up. Try preg_split
$lines = preg_split("/\\n|\\r|\\r\\n/", $str);
Related
In our website, we have textbox to ask input values from user. If user input the data Q54497899, rest of the results must be shown from database. Rightnow, I want to add checkbox on each result. I tried to add with foreach but it still doesn't work for me. I will provide codes below which were written in the correlationwafer_result.php. Want to add checkbox beside each Q54497899
<?php
// ini_set("memory_limit","512M");
include("_dbconn.php");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/db_config.inc");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/standard_defines.inc");
session_start();
$productlotid = isset ($_GET['productlotid'])? $_GET['productlotid']:'';
$sql = "SELECT * FROM productdb.tbl_correlationwafer WHERE `lotid` = '$productlotid'";
$result1 = mysqli_query($conn,$sql);
$cnt = 0;
echo "<table id='corwafer'>";
while ($row = mysqli_fetch_assoc($result1)) {
echo "<tr>";
echo "<th colspan='2'>Lot ID:</th>";
echo "<th colspan='2'>Product:</th>";
echo "<th colspan='4'>EWSFLOW </th>";
echo "<th>Zone</th>";
echo "</tr>";
$field1name = $row["lotid"];
$field2name = $row["product"];
$field3name = $row["ewsflow"];
$field4name = $row["zone"];
echo '<tr>
<td colspan="2">'.$field1name.'</td>
<td colspan="2">'.$field2name.'</td>
<td colspan="4">'.$field3name.'</td>
<td >'.$field4name.'</td>
</tr>';
foreach($productlotid as $k => $v){
if($k == $row["lotid"]){
echo "<input type=\"checkbox\" id=\"chkproductlotid" . $cnt . "\" name=\"chkproductlotid\" value=\"$v\"><font face=\"arial\" size=\"2\" color=\"#3C5F84\">". $k . "</font>";
}
}
$cnt++;
}
echo "</table>";
flush();
mysqli_close($conn);
?>
Try :
$('chkproductlotid').val();
$productlotid = isset ($_GET['productlotid'])? $_GET['productlotid']:'';
Your $productlotid is more like a string not an array, does it?
You should put your checkbox inside td, and I think your checkbox value should be able to take from the first While Loop, no need that Foreach..
I am writing an application in which user can enter a database name and I should write all of its contents in table with using PHP.I can do it when I know the name of database with the following code.
$result = mysqli_query($con,"SELECT * FROM course");
echo "<table border='1'>
<tr>
<th>blablabla</th>
<th>blabla</th>
<th>blablabla</th>
<th>bla</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['blabla'] . "</td>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['bla'] . "</td>";
echo "</tr>";
}
echo "</table>";
In this example I can show it since I know the name of table is course and it has 4 attributes.But I want to be able to show the result regardless of the name the user entered.So if user wants to view the contents of instructors there should be two columns instead of 4.How can I accomplish this.I get the table name with html.
Table:<input type="text" name="table">
Edit:Denis's answer and GrumpyCroutons' answer are both correct.You can also ask me if you didnt understand something in their solution.
Quickly wrote this up, commented it (This way you can easily learn what's going on, you see), and tested it for you.
<form method="GET">
<input type="text" name="table">
</form>
<?php
//can be done elsewhere, I used this for testing. vv
$config = array(
'SQL-Host' => '',
'SQL-User' => '',
'SQL-Pass' => '',
'SQL-Database' => ''
);
$con = mysqli_connect($config['SQL-Host'], $config['SQL-User'], $config['SQL-Pass'], $config['SQL-Database']) or die("Error " . mysqli_error($con));
//can be done elsewhere, I used this for testing. ^^
if(!isSet($_GET['table'])) { //check if table choser form was submitted.
//In my case, do nothing, but you could display a message saying something like no db chosen etc.
} else {
$table = mysqli_real_escape_string($con, $_GET['table']); //escape it because it's an input, helps prevent sqlinjection.
$sql = "SELECT * FROM " . $table; // SELECT * returns a list of ALL column data
$sql2 = "SHOW COLUMNS FROM " . $table; // SHOW COLUMNS FROM returns a list of columns
$result = mysqli_query($con, $sql);
$Headers = mysqli_query($con, $sql2);
//you could do more checks here to see if anything was returned, and display an error if not or whatever.
echo "<table border='1'>";
echo "<tr>"; //all in one row
$headersList = array(); //create an empty array
while($row = mysqli_fetch_array($Headers)) { //loop through table columns
echo "<td>" . $row['Field'] . "</td>"; // list columns in TD's or TH's.
array_push($headersList, $row['Field']); //Fill array with fields
} //$row = mysqli_fetch_array($Headers)
echo "</tr>";
$amt = count($headersList); // How many headers are there?
while($row = mysqli_fetch_array($result)) {
echo "<tr>"; //each row gets its own tr
for($x = 1; $x <= $amt; $x++) { //nested for loop, based on the $amt variable above, so you don't leave any columns out - should have been <= and not <, my bad
echo "<td>" . $row[$headersList[$x]] . "</td>"; //Fill td's or th's with column data
} //$x = 1; $x < $amt; $x++
echo "</tr>";
} //$row = mysqli_fetch_array($result)
echo "</table>";
}
?>
$tablename = $_POST['table'];
$result = mysqli_query($con,"SELECT * FROM $tablename");
$first = true;
while($row = mysqli_fetch_assoc($result))
{
if ($first)
{
$columns = array_keys($row);
echo "<table border='1'>
<tr>";
foreach ($columns as $c)
{
echo "<th>$c</th>";
}
echo "</tr>";
$first = false;
}
echo "<tr>";
foreach ($row as $v)
{
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
<?php
$table_name = do_not_inject($_REQUEST['table_name']);
$result = mysqli_query($con,'SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='. $table_name);
?>
<table>
<?php
$columns = array();
while ($row = mysql_fetch_assoc($result)){
$columns[]=$row['COLUMN_NAME'];
?>
<tr><th><?php echo $row['COLUMN_NAME']; ?></th></tr>
<?php
}
$result = mysqli_query($con,'SELECT * FROM course'. $table_name);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>';
foreach ($columns as $column){
?>
<td><?php echo $row[$column]; ?></td>
<?php
}
echo '</tr>';
}
?>
</table>
I am building an page the script is done it lists Name and Points in a table. But when i gonna do the design it will be to hard to do it with "echo". So i am woundering if i can get this into vars insted that i can just use in a html file.
Table look like this
Name | Points | Date
What i want is to make a var for the 10 first name rows and a var for the 10 first point rows.
Like
$top1n = $row[0]'name'
$top1p = $row[0]'points'
$top2n = $row[1]'name'
$top2p = $row[1]'points'
$top3n = $row[2]'name'
$top3p = $row[2]'points'
$top4n = $row[3]'name'
$top4p = $row[3]'points'
And so on...
etc.
See my script below
echo "<table border='1'>";
echo "<tr> <th>Name</th> <th>Tokens</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $resultbtm )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['Name'];
echo "</td><td>";
echo $row['points'];
echo "</td></tr>";
}
echo "</table>";
Is this what you want?
$names = array();
$points = array();
while($row = mysql_fetch_array($resultbtm)) {
$names[] = $row['Name'];
$points[] = $row['tokens'];
}
echo '<pre>';
print_r($names);
print_r($points);
echo '</pre>';
Not 100% sure if this is what you were looking for, but the $names and $points variables will be arrays containing the Names and Tokens (respectively) from your mysql result set.
Side note: mysql_* functions are deprecated as of PHP 5.5.0 due to security issues. If you are able to it is strongly recommended you switch to mysqli_* or PDO.
You can do it like this: (no need to create so many variables)
$str = "<table border='1'>";
$str .= "<tr> <th>Name</th> <th>Tokens</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $resultbtm )) {
// Print out the contents of each row into a table
$str .= "<tr>";
$str .= "<td>".$row['Name']."</td><td>".$row['points']."</td>";
$str .= "</tr>";
}
$str .= "</table>";
echo $str;
You could use extract
echo "<table border='1'>";
echo "<tr> <th>Name</th> <th>Tokens</th> </tr>";
// keeps getting the next row until there are no more to get
$c = 1;
while($row = mysql_fetch_array( $resultbtm )) {
${'top'.$c.'n'} = $name;
${'top'.$c.'p'} = $points;
$c++;
// Print out the contents of each row into a table
echo "<tr><td>$Name</td><td>$tokens</td></tr>";
}
echo "</table>";
I want to print a list from a mysql database, but the first list item isn't printing because mysql_fetch_array is called twice. I tried reset but it didn't work. What should I do?
$current_goam = mysql_real_escape_string($current_goam);
$current_content = mysql_real_escape_string($current_content);
$note_content = mysql_query("select * from notes where title='$current_content' and goam='$current_goam' and user_id='$user_id'");
$note = mysql_fetch_array( $note_content );
if($note['type'] == 'list')
{
$note_type='list';
reset($note);
print "<table>";
while($note_info = mysql_fetch_array( $note_content ))
{
print "<tr><td>";
echo $note_info['body'];
print "</td>";
echo "<td><input type='checkbox' name='complete_goal' value='".$note_info['note_id']."'></input></td>";
print "</tr>";
}
print "</table>";
}
else{
echo $note['body'];
}
try this instead of reset
mysql_data_seek($note_content, 0);
reset works for arrays
Try to load data in array and then use it as you whant
$records = array();
while($r = mysql_fetch_array($note_content)) {
$records[] = $r;
}
i want to echo out everything from a particular query. If echo $res I only get one of the strings. If I change the 2nd mysql_result argument I can get the 2nd, 2rd etc but what I want is all of them, echoed out one after the other. How can I turn a mysql result into something I can use?
I tried:
$query="SELECT * FROM MY_TABLE";
$results = mysql_query($query);
$res = mysql_result($results, 0);
while ($res->fetchInto($row)) {
echo "<form id=\"$row[0]\" name=\"$row[0]\" method=post action=\"\"><td style=\"border-bottom:1px solid black\">$row[0]</td><td style=\"border-bottom:1px solid black\"><input type=hidden name=\"remove\" value=\"$row[0]\"><input type=submit value=Remove></td><tr></form>\n";
}
$sql = "SELECT * FROM MY_TABLE";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!! Check summary get row on array ..
echo "<tr>";
foreach ($row as $field => $value) { // I you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>"; // I just did not use "htmlspecialchars()" function.
}
echo "</tr>";
}
echo "</table>";
Expanding on the accepted answer:
function mysql_query_or_die($query) {
$result = mysql_query($query);
if ($result)
return $result;
else {
$err = mysql_error();
die("<br>{$query}<br>*** {$err} ***<br>");
}
}
...
$query = "SELECT * FROM my_table";
$result = mysql_query_or_die($query);
echo("<table>");
$first_row = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first_row) {
$first_row = false;
// Output header row from keys.
echo '<tr>';
foreach($row as $key => $field) {
echo '<th>' . htmlspecialchars($key) . '</th>';
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
echo("</table>");
Benefits:
Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.
Shows field names as a header row of table.
Shows how to get both column name ($key) and value ($field) for each field, as iterate over the fields of a row.
Wrapped in <table> so displays properly.
(OPTIONAL) dies with display of query string and mysql_error, if query fails.
Example Output:
Id Name
777 Aardvark
50 Lion
9999 Zebra
$result= mysql_query("SELECT * FROM MY_TABLE");
while($row = mysql_fetch_array($result)){
echo $row['whatEverColumnName'];
}
$sql = "SELECT * FROM YOUR_TABLE_NAME";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!!
echo "<tr>";
foreach ($row as $field => $value) { // If you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
In PHP 7.x You should use mysqli functions and most important one in while loop condition use "mysqli_fetch_assoc()" function not "mysqli_fetch_array()" one. If you would use "mysqli_fetch_array()", you will see your results are duplicated. Just try these two and see the difference.
Nested loop to display all rows & columns of resulting table:
$rows = mysql_num_rows($result);
$cols = mysql_num_fields($result);
for( $i = 0; $i<$rows; $i++ ) {
for( $j = 0; $j<$cols; $j++ ) {
echo mysql_result($result, $i, $j)."<br>";
}
}
Can be made more complex with data decryption/decoding, error checking & html formatting before display.
Tested in MS Edge & G Chrome, PHP 5.6
All of the snippets on this page can be dramatically reduced in size.
The mysqli result set object can be immediately fed to a foreach() (because it is "iterable") which eliminates the need to maked iterated _fetch() calls.
Imploding each row will allow your code to correctly print all columnar data in the result set without modifying the code.
$sql = "SELECT * FROM MY_TABLE";
echo '<table>';
foreach (mysqli_query($conn, $sql) as $row) {
echo '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
}
echo '</table>';
If you want to encode html entities, you can map each row:
implode('</td><td>' . array_map('htmlspecialchars', $row))
If you don't want to use implode, you can simply access all row data using associative array syntax. ($row['id'])