This PHP code takes records from my database and displays them. Basically, I want every occurrence of the string "cross" (lowercase only) to be changed to an image that is on my web server.
Records currently look like: crossJohn Doe. So when it appears on the page, it should replace cross with the img and keep the rest.
The code:
$sql = "SELECT DisplayName, LastName, FirstName FROM donor WHERE DonationAmount = 1000 ORDER BY LastName ASC LIMIT 154";
$result = mysqli_query($conn, $sql); // query
if (mysqli_num_rows($result) > 0) { // as long as the query returns something, do the calcs.
$array = array(); // create a variable to hold the information
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ // whule there are results, put them in the array
$array[] = $row; // add the row in to the results (data) array
}
$counter = (count($array)); // find the amount of items in the array
$divisorCount = ceil($counter/2); // column count
$forEachCount = 1;
//loop while there are items in the array
foreach ($array as $row){
$forEachCount++; //increment counter
// naming logic
if (empty($row['DisplayName'])) { // if there is no DisplayName
if (empty($row['FirstName'])) { // show lastname
$block[] = "<div class='block'>".$row['LastName']."</div>\n";
}
else { //show first + last if no display name
$block[] = "<div class='block'>".$row['FirstName']." ".$row['LastName']."</div>\n";
}
} else { // show display name
$block[] = "<div class='block'>".$row['DisplayName']."</div>\n";
}
if($forEachCount > $divisorCount){ //insert each record into a "block"
$forEachCount = 0;
end($block);
$key = key($block);
$block[$key] .= "</div><div class='column'>"; // insert all "blocks" into a css div
}
}
unset($row,$key,$forEachCount,$divisorCount); //cleanup
//insert the div and populate it with the blocks
$output = "<div class='tableContainer'>
<div class='column'>".implode($block)."</div>
</div>";
print_r($output); // display all of it!
unset($array,$block);
}else{echo "<p>There are no donors in this category.</p>";}
using the REPLACE mysql string function might be enough
$sql = "SELECT REPLACE(DisplayName,'cross','<img src=\"path/to/image\" />') AS `DisplayName`, REPLACE(LastName,'cross','<img src=\"path/to/image\" />') AS `LastName`, REPLACE(FirstName,'cross','<img src=\"path/to/image\" />') AS `FirstName` FROM donor WHERE DonationAmount = 1000 ORDER BY LastName ASC LIMIT 154";
-- http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace
you can use mysqli_fetch_assoc instead of using mysqli_fetch_array and adding another argument to get only the associative one
while ($row = mysqli_fetch_assoc($result)) {
if (stripos('cross',$row['keyname']) !== false)
$row['keyname'] = str_replace('cross','<img src="path/to/image"/>',$row['keyname']);
$array[] = $row; // add the row in to the results (data) array
}
Related
I have column name called as email. In that, I have more than 100 rows. Some rows have more than 10 records with a comma(,) some have only 1 records. I have to display all the records in one line.
This is my table
I am getting output like
The output I need in one line so that I can export it.
$sql ="SELECT email FROM email12";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$a=$row['email'];
$b = explode(',',$a);
echo '<pre>'; print_r($b);echo '<pre>';
}
}
I would iterate through exploded array:
$sql ="SELECT email FROM email12";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$a=$row['email'];
$b = explode(',',$a);
foreach($b as $email) {
echo '<pre>'; print_r($email);echo '<pre>';
}
}
}
From the database's perspective, it's not recommended and certainly not a good practice to have data as comma separated list. You should consider normalizing your database. Having said that, you should follow the below procedure to achieve the desired result as of now(or for the time being).
Create an empty array(for example, $resultArr) before the beginning of while loop. In each iteration of while loop, explode email column value and append them to $resultArr array. Finally, after coming out of the loop, simply perform implode operation on the resultant array to display all the records in one line.
$sql ="SELECT email FROM email12";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$resultArr = array();
while($row = $result->fetch_assoc()) {
$resultArr[] = explode(',',$row['email']);
}
echo implode(',', $resultArr);
}
I want to output all image files of a specific productid. What is the right syntax to output the image path for row 1, row 2, row 3 etc? I can not find it.
$sql = "SELECT *
FROM images
WHERE productid = $productid";
$select = $db->prepare($sql);
$select->execute(array());
foreach($select as $index => $rs) {
if($rs['imagepath']){
if($index == 0){
echo $imagepath[0]; // <---What is the right sytax of this?
}
}
if($rs['imagepath']){
if($index == 1){
echo $imagepath[1]; // <---and this?
}
}
if($rs['imagepath']){
if($index == 3){
echo $imagepath[2]; // <---and this?
}
}
The whole point of a foreach loop is it goes once through each select as "index". so you shouldn't have to worry about making an if-statement for each possible row, just make the statement once, and it will happen on each and every iteration
$rows = [];
$sql = "SELECT *
FROM images
WHERE productid = productid";
$select = $db->prepare($sql);
$select->execute(array());
foreach($select as $index => $rs) {
$rows []= $rs;
}
echo $rows[0]['imagepath'];
aren't we missing the fetch function?
`
$select = $db->prepare($sql);
$select->execute(array());
$i = 0;
while($row = $select->fetch()) {
echo $i . ' '. $row['imagepath'] . '<br>';
$i++;
}
?>
`
--
addendum:
I now understand you only want one, or some, of the images to be shown.
Would it not be easier then, to only select that/those images?
SELECT imagepath
FROM images
WHERE productid = productid
AND someid = 3
or if no "someid" is present:
SELECT imagepath
FROM images
WHERE productid = productid
LIMIT 2,1
That would avoid the need to loop through may be 100 records to only use the 3th.
$query = "select * from tableitem";
$result = mysql_query($query);
$col = array();
while ($row = mysql_fetch_array($result)){
//they have computation here inside loop.
$amount = $value;
if($row['status']>3){ // base on the status only
if($amount>0){ //base on the computation
$count = $item;
// i need to count here the item before the grouping of duplicate item below.
if (!isset($col[$row['item']])) { // this is working for grouping the duplicate value
echo $row['item'];
echo $count; // count item
$col[$row['item']] = true;
}
}
}}
Sample output should be like this inside while loop if possible.
Item one 2
Item two 3
Item five 4
You can do that with sql not necessary php;
SELECT COUNT(*) as N,item
FROM tableitem
GROUP BY item
it will return duplicate items and you can check with n>1. And you can add more column for group.
$itemArray;
while ($row = mysql_fetch_array($result)){
if($row['n']>1){
itemArray[] = $row['item'];
}
}
print_r($itemArray);
If you increment array values using the keys you are trying to count:
$check = array();
foreach($values as $key => $value) {
if (isset($check[$key])) {
$check[$key]++;
} else {
$check[$key]=1;
}
}
var_dump($check);
I would want to create an array that will hold records retrieved from a database using a query of SELECT statement.
The records to be retrieved have multiple fields such as lastname, firstname, mi and 20 more fields. What would be the best approach on coding this function?
alright i have followed what prisoner have given below.. the next question is how do i search through this kind of array using queries? for example i want to search for a username..
<?php
// run query
$query = mysql_query("SELECT * FROM table");
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
// OR just echo the data:
echo $row['username']; // etc
}
// debug:
print_r($array); // show all array data
echo $array[0]['username']; // print the first rows username
You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:
if (isset($_GET['search'])) {
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT * FROM users WHERE username = '$search'";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($res);
if ($row){
print_r($row); //do whatever you want with found info
}
}
$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
$c++;
}
for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}
$memberId =$_SESSION['TWILLO']['Id'];
$QueryServer=mysql_query("select * from smtp_server where memberId='".$memberId."'");
$data = array();
while($ser=mysql_fetch_assoc($QueryServer))
{
$data[$ser['Id']] =array('ServerName','ServerPort','Server_limit','email','password','status');
}
I have an array, $scans. I want to query MySQL with all the values in that array and get my results back in an array. For example, sample data in scans would be:
E1234
E2244
E3654
The MYSQL table PARTS has fields part, size, length, plate, side, type.
I want to end up with $output["E1234"][0] to be the size result for that part, 1 to be length, etc. and I want the array to be sortable by the MYSQL query. (order by SIDE desc, PLATE asc).
Right now, i'm just stepping through the $SCANS array and doing query after query, but I'm not able to then sort all the results properly.
Is this possible? This is what I'm doing now, but obviously since each query returns one row which is then outputted, there's no sortability. I want to be able to perform one query, sort the results within the array, and then output that data after the sort.
foreach ($scans as $currentscan) {
$partselect = substr(mysql_real_escape_string($currentscan), 0, 5);
$query = "SELECT french, length, plate, side, type FROM parts WHERE part = '$partselect' ORDER BY side DESC, plate ASC LIMIT 1";
$result = mysql_query($query);
#echo 'query is '.$query.' <br>';
$error = mysql_error();
$num_rows = mysql_num_rows($result);
if ($num_rows == 0) {
echo 'BAD PART: '.$currentscan.' '.$partselect.' error is '.$error.'<br \>
';
} else {
$row = mysql_fetch_array($result);
print $partselect.' is a '.$row['french'].'/'.$row['length'].' - '.$row['type'].' - '.$row['plate'].'('.$row['side'].')<br \>';
}
};
EDIT: This is the code as it is now following some suggestions here:
$scans = explode("\n",$_POST['scans']);
foreach ($scans as $currentscan) {
if ($currentscan[0] == "E") { //this is a cheap trick to ignore a bad scan inherent in the scanning mechanism
$partselect = substr(mysql_real_escape_string($currentscan), 0, 5);
$tempQuery .= 'part = "'.$partselect.'" OR ';
};
};//end foreach
$tempQuery = substr($tempQuery, 0, -3); //remove last OR (fixed substr to 0,-3 to scrip final OR - stephen)
$tempQuery .= ") ORDER BY side DESC, plate ASC LIMIT 1"; //add on end of query
$query = "SELECT french, length, plate, side, type FROM parts WHERE ".$tempQuery;
$result = mysql_query($query);
echo $result;
while($row = mysql_fetch_array($result)){
print $row['french']." / ".$row['length']; //just doing something pointless to verify data was pulled.
}
result is:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/foo/bar/sort.php on line 35
Line 35 is
while($row = mysql_fetch_array($result)){
FINAL EDIT:
It works.
//DECLARED CONSTANTS//
if (!$_POST) { // Have scans been entered? If not, display the form.
print '
<html>
<body>
Scans:
<form action="index.php" method="post">
<textarea rows="20" cols="6" name="scans" id="scans">
</textarea>
<br />
<input type="submit" value="Submit" />
</body>
</html>
';
} else { //Scans have been entered. Start scan processing logic
//==openDB==//
mysql_connect(SQLSERVER, SQLUSER, SQLPASSWORD) or die("Can not connect to DB server.");
mysql_select_db(DATABASE) or die("Can not connect to Database.");
//==openDB==//
$scans = explode("\n",$_POST['scans']); // Explode posted scans into scans array
foreach ($scans as $currentscan) { // step through each scan
if ($currentscan[0] == "E") { //Cheap check for real part numbers.
$partselect = substr(mysql_real_escape_string($currentscan), 0, 5); // Strip off the extraneous data from the scan
$count{$partselect}++; //Count instances of particular parts. ideally this would be in an array in the form of $count[$partnumber] so I can easily display that data at the end. each part needs to be displayed every time it's scanned.
$tempQuery .= 'part = "'.$partselect.'" OR '; //Starts building query
};
};//end foreach
$tempQuery = substr($tempQuery, 0, -3); //remove last OR
$tempQuery .= ") ORDER BY side DESC, plate ASC"; //add on end of query
$query = "SELECT part, french, length, plate, side, type FROM parts WHERE (".$tempQuery; //Form beginning of query
$result = mysql_query($query);// execute query
while($row = mysql_fetch_array($result)){ // step through results
for ($i = 0; $i < $count{$row['part']}; $i++) { //if a part was scanned $count{$row['part']} times, display it that many times
print $row['part']." ".$row['french']." / ".$row['length']." ".$row['plate']."(".$row['side'].")<br>"; //data parsing goes here. this will be expanded.
};// close for loop
};//close while loop
};//close else
?>
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['name']. " - ". $row['age'];
?>
Courtesy of http://www.tizag.com/mysqlTutorial/mysqlfetcharray.php
You can also if you expect multiple results do:
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['age'];
}
?>
Added code for your comment:
foreach ($scans as $currentscan) {
$partselect = substr(mysql_real_escape_string($currentscan), 0, 5);
$tempQuery .= "(part = ".$partselect." OR";
}//end foreach
$tempQuery = substr($tempQuery,-2); //remove last OR
$tempQuery .= ") ORDER BY side DESC, plate ASC LIMIT 1"; //add on end of query
$query = "SELECT french, length, plate, side, type FROM parts WHERE ".$tempQuery;
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
//do something with row in result set...
}
Whay you should do is to construct a WHERE clause in PHP, which lets you select all rows that have any of the part numbers. Something like this:
$whereExpr = array();
for ($i = 0; $i < count($scans); $i++) {
$whereExpr[] = "part = \"{$scans[$i]}\"";
}
$whereExpr = implode(" OR ", $whereExpr);
$query = "SELECT * FROM `parts` WHERE $whereExpr ORDER BY <whatev>";
$result = array();
while ($row = mysql_fetch_array) {
$result[ $row['part'] ] = $row;
}
MySQL Fetch Array Function
After looking at your update/edit you could use the IN clause
// Represents your $scans array
$arr = array('Hello','World!','Beautiful','Day!');
foreach ($arr as $currentscan) {
$partselect[] = substr(mysql_real_escape_string($currentscan), 0, 5);
}
$inExpr = implode("','",$partselect);
$query = "SELECT french, length, plate, side, type FROM parts WHERE part IN('$inExpr') ORDER BY side DESC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
print $partselect.' is a '.$row['french'].'/'.$row['length'].' - '.$row['type'].' - '.$row['plate'].'('.$row['side'].')<br \>';
}