I am using a with statement for values in a table cell. Prior to inserting this statement all was fine. All I am trying to do is to change the color label on the text depending on the string value, but now the Cell is blank which tells me that none of the cases are true. I suspect that if there was an error instead then the cells after the statement would also be blank, but they are complete.
If I had to guess, I would say there is an error in the string declaration, but I am not sure.
<?php
$result = mysql_query("SELECT * FROM logs ORDER BY logid DESC");
while($data = mysql_fetch_array($result))
{
echo '<tr>
<td>'.$data["logid"].'</td>
<td class="center">'.$data["date"].'</td>
<td class="center">';
$log_type='.$data["log_type"].';
switch ($log_type) {
case "Check in":
echo '<span class="label label-success">'.$data["log_type"].'</span>';
break;
case "Log":
echo '<span class="label">'.$data["log_type"].'</span>';
break;
case "Sensor Event":
echo '<span class="label label-important">'.$data["log_type"].'</span>';
break;
}
echo '</td>
<td class="center">'.$data["log_entry"].'</td>
<td class="center">'.$data["customer_id"].'</td>
</tr>';
}
?>
The full code block simply reads data from a mysql table and spits it out in a nice table format into a website. By using different CSS classes, I can change the label color.
Question is why is this Case only a blank cell?
UPDATE: for those of you reading this and looking for the specific answer I have changed the line:
$log_type='.$data["log_type"].';
to
$log_type=$data["log_type"];
and that fixed it.
It's a pretty obvious mistake. Variables under single quotes will not be parsed which is what you have done. With your current code, $log_type will have the value .$data["log_type"]. (tested)
So, your code of:
$log_type= '.$data["log_type"].';
should be:
$log_type= $data["log_type"];
If you want single quotes around the value, you should do:
$log_type = "'".$data["log_type"]."'";
$data holds your result set array.
In this line :
$log_type='.$data["log_type"].';
you are accesing the result set in incorrcet manner, to access the attributes of the result set, you just have to enclose them in quotes against the object ( $data in this case ) holding the array.Below is the correct way to solve it :
$log_type=$data["log_type"];
to concat or enclose your solution in ' :
"'".$log_type."'" OR "'".$data["log_type"]."'"
Related
I have a table where is one week displayed (each row is one day).
I get the rows from a while loop from my database. The rows are displayed in bootstrap accordions.
There is a textarea in every accordion row where the user can input (update) some text.
I want to update this text into my database. It should update the text depending on the day id.
<form method="POST" action="">
<table class="table table-hover" style="border-collapse:collapse;">
<thead>
<tr>
<th>Weekday</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php
// Select Statement (for shortening not included into this Stack question)//
while($row = $statement->fetch()) {
$thedate = $row['Date'];
$weekday=strftime("%A", strtotime($thedate));
$date=date('d-m-Y', strtotime($thedate));
echo "<tr data-toggle='collapse' data-target=#".$row['Date']." class='clickable collapse-row collapsed'>";
echo "<td >".$weekday."</td>";
echo "<td>".$date."</td>";
echo" <td style='color:black; font-size:20px;'><i class='fas fa-angle-down'></i></td>";
echo "</tr>";
echo "<tr><div class='accordian-body collapse' id=".$row['Date'].">
<td colspan='1' class='hiddenRow'><textarea name=".$row['id']." rows='5' cols='80'>".$row['Text']." </textarea></td>
//the $row['id'] should give every textarea a unique dayid from my database
echo"</td>
</div></tr>";
}
if(ISSET($_POST['id'])){
$debug=$_POST['id'];
}
var_dump($debug); // var_dump for debugging. See text below
?>
</tbody>
</table>
<button type="submit" name="Speichern" class="btn btn-lg btn-primary btn-block">Speichern</button>
</form>
Before writing the Sql Update Statement I wanted to debug to find possible bugs.
If i debug this with var_dump I get the error message "Undefined variable $debug" and I dont know why. The variable shouldnt be empty because in the textareas is always text.
Im new to PHP and coding at all so probably Im making a dump mistake.
EDIT: If I put the var_dump inside the if condition i get nothing as return.
I tried it also with the var_dump in the if block but then i get nothing as return.
That’s because you do not have any form field that is actually named id. You put name=".$row['id']." on your textarea, and that is likely a numeric value. And you probably don’t know which one that will be, on the receiving end.
Plus, since you are creating multiple such fields in a loop, PHP will overwrite all values for this parameter with the last one. You need to use a naming scheme that includes square brackets to avoid that, something like name="foo[]" - then $_POST['foo'] will become an array that you can loop over.
And since you will still need your record ID to associate with the data, you can put that into the brackets, name="foo[123]" – then this 123 will become the key of that array element, for this specific textarea.
If you loop over that using the extended foreach syntax, then you have easy access to the ID, and the value entered by the user:
foreach( $_POST['foo'] as $id => $value ) { … }
How do I use php so it tests if a value in a mysql table is equal to a string? I am making a bans list and theres several categories, mutes, warnings and bans. The problem at the moment is they all display in every category so bans, mutes, warnings display in bans, mutes and warnings. They aren't sorted. I tried to fix it by using
<td>
<?php
if($row['punishmentType'] == 'BAN') {
echo "<img src='https://mcapi.ca/avatar/2d/" . $row['name'] . "/25' style='margin-bottom:5px;margin-right:5px;border-radius:2px;' />" . $row['name'];
}
else {
echo 'ERROR'
}
?>
</td>
But it comes up with ERROR. In the mysql table, theres 3 punishment types, BAN, MUTE and WARNING. Can someone tell me whats wrong with the code above? And how I fix it.
First of all you should check if $row['punishmentType'] has content. Then you can use a switch statement to separate your logic according to the type of punishment.
You could do:
<?php
if(!empty($row['punishmentType'])) {
switch($row['punishmentType']) {
case 'BAN': ...
break;
case 'MUTE': ...
break;
case 'WARNING': ...
break;
}
I have a form
<form action="_orders.php" method="get" autocomplete="off" name="cerca_db">
<tr>
<td class="main" width="170">Ricerca Cliente</td>
<td><input type="hidden" name="action" value="check_sped_data" /></td>
<td class="main"><p class="ciao" id="auto"><input id="searchField" name="searchField" type="text" onKeyPress="return disableEnterKey(event)"></p></td>
<td width="25"></td>
<td class="main"><input type="submit" value="Cerca"></td>
</tr>
</form>
This is used to search in a mysql db table. Once the button is clicked it autocompletes all fields of another form based on the database record just found.
Now my problem is with autocomplete part because of case sensitive. I have already managed to extract data in lower case but i'm not able to transform input
searchField to lower case before send to java function to match db record.
I actually found javascipt function to have autocomplete stuff. I only changed html and php part to match my needs, I didn't touch anything on java itself because i'm totaly a noob with it.
So now the form send the input to the javascript like this
$(function(){
setAutoComplete("searchField", "results", "autocomplete.php?part=");
});
The automcomplete.php is need to extract data from db based on input and place in array to display under the input:
$result = mysql_query("SELECT a.customers_firstname, a.customers_lastname, a.customers_id, b.entry_company FROM customers a left join address_book b on a.customers_id = b.customers_id GROUP BY b.entry_cf");
while ($row = mysql_fetch_assoc($result))
{
$ricerca = array(strtolower($row['customers_firstname']) => strtolower($row['customers_lastname']));
foreach ($ricerca as $key=>$data)
{
$edata[]=$data . ' ' . $key;
$edata[].=$key .' ' . $data;
}
$edata[].=(strtolower($row['entry_company']));
}
Now we have the array of names and company all lower case ready to match what is entered in the field. If the input is lowercase everything works fine, but if input is uppercase it doesn't match anything at all.
Do you guys have any solution on this or any idea how i can workout the case sensitive problem?
Edited: this is how data are pushed from db to the java script:
if(isset($_GET['part']) and $_GET['part'] != '')
{
$results = array();
$count = 0;
foreach($extracted_data as $edata)
{
if( strpos($edata, $_GET['part']) === 0 )
{
$results[] = $edata;
$count++;
if ($count == 10) break;
}
}
echo json_encode($results);
}
Before submitting or sending information, call a javascript function which converts all characters to lowercase.
If your element is named "YourInputID",
Example:
function convert()
{
var a = document.getElementById("YourInputID").value;
a = a.toString().toLowerCase();
document.getElementById("YourInputID").value = a;
}
You could use javascript string function reference here str.toLowerCase() to convert the string characters to lower.
This should get you on the right track:
document.getElementById('foo').addEventListener('keypress', function(e) {
e.preventDefault();
this.value += String.fromCharCode(e.keyCode).toLowerCase();
});
Demo: http://jsfiddle.net/m66c2/
OK, firstly your PHP is going to have some problems. Where you say:
$edata[]=$data . ' ' . $key;
$edata[].=$key .' ' . $data;
That's going to access two different items in the array, which I assume you don't want to do. That's because the syntax $array[] is (sort of) short for using the array_push() method - each time it is accessed it adds to the array. The syntax $array[].=$value means the same as $array[]=$value as you can't effectively concatenate to an empty array item.
$edata_this='';
foreach ($ricerca as $key=>$data)
{
$edata_this=$data . ' ' . $key;
$edata_this.=$key .' ' . $data;
}
$edata_this.=(strtolower($row['entry_company']));
$edata[]=$edata_this;
Now, if your issue is simply converting a JavaScript item to lower case, use the String.toLowerCase() method.
However I'm not entirely sure in the question which part you're actually needing to change or do a comparison on, so some more explanation might be useful.
Additionally you should always avoid using inline JavaScript such as onKeypress; as you're using jQuery try using its $().keypress() binding:
$('input[name="YOUR_NAME"]').keypress(function(){
// your actions go here
});
I have been working on this one topic for weeks. I'm creating a webpage that pulls information from MsSQL server. My problem is where there is a section with few check boxes.
The checkboxes are suppose to be checked if they are found in the SQL database.
If the borrower used money from "Savings", "Checking" and "Stock" those checkboxes should be checked in HTML page. In my case it is only checking whatever is on the first row of the SQL search list. So if the list has "Saving" on the first row, only the "Saving" checkbox will be checked not the rest on the list. I tried using loop (while($r->EOF)), but then it picks whatever is on the end of the list. Here is what I am using to pull data from the SQL server. Thank you in advance for your help. Really appreciate it!
function __construct($_ldid, $_lrid)
$this->ldid = $_ldid;
$this->lrid = $_lrid;
//$loan is defined in the PHP.class (which is shown below).
$q = ("SELECT * FROM Tabel_name where loan_id = 885775")
$v = array($_ldid, $_lrid);
$r = $db->Execute($q, $v);
$this->downpaymenttype = $r->fields; //<- I think I have this line done wrong because it is suppose to store the outputs to an array.
//So wherever the "$loan" is in HTML page, it will take the outputs from the above statement.
//The above code, which is in PHP.class file, outputs the following(or suppose to):
1 885775 Checking
2 885775 Saving
3 885775 Gift
In the HTML webpage, the following codes should check mark the boxes according to the outputs:
<input type="checkbox" name="DPS1[]" id="DPS1-{$key}" {if $loan-> downpaymenttype.downpaymentsource == "Checking"} checked {/if}/>
<input type="checkbox" name="DPS2[]" id="DPS2-{$key}" {if $loan-> downpaymenttype.downpaymentsource == "Saving"} checked {/if}/>
<input type="checkbox" name="DPS3[]" id="DPS3-{$key}" {if $loan-> downpaymenttype.downpaymentsource == "Gift"} checked {/if}/>
Only the "checking" checkbox is getting checked because that's the one on the first row.
I also tried to loop, but it is not storing in array (I guess I don't know how to use the array for session)
$q = ("SELECT Tabel_name FROM loan_downpaymentsource where loan_id = 885775");
$v = array($_ldid, $_lrid));
$r = $db->Execute($q, $v);
while(!$r->EOF) {
$this->downpaymenttype = $r->fields;
$r->MoveNext();
}
Add a loop to go through your results before displaying and set flags. $r->fields is only going to grab the fields for the current row. You need to go through your entire rowset to see if the others are set.
Something like (It looks like you're using adodb or something like that)
$checking = false;
$saving = false;
$gift = false;
while(!$r->EOF){
$row = $r->fields;
switch($row->downpaymenttype){
case 'Checking':
$checking=true;
break;
case 'Saving':
$saving=true;
break;
case 'Gift':
$gift=true;
break;
default:
break;
}
$r->moveNext();
}
Now on your view check the flags. I've not used smarty but you'll have to pass those flags to your template as well as I'm sure you know, and then change your checkbox lines to check if each flag is true/false.
Hope that helps!
An SQL query gives no output through AJAX page when variables are passed in the query. Even the count of number of rows gives zero (0). An echo of the same query with the passed variables shows as having values.
When copy and pasting the same (replacing) from the browser page to the query in the AJAX page it gives a result.
The code is as follows (first SQL code in AJAX page with variables as parameter):
$qu="SELECT DISTINCT bk.bookname,bk.author,bk.publisher,bk.edition,bk.description,lam.article_name,bk.keywords,bk.qtyinstock FROM lib_article_master lam, lib_book_cd_master bk WHERE bk.bookname='$arr[2]' AND bk.author='$arr[3]' AND bk.publisher='$arr[4]' AND bk.article_id=lam.article_id";//here $arr[2],$arr[3],$arr[4] are variables from another query for comparison in AJAX page
$r=QrySelect($qu);
echo " <br> ".$qu;//query is echoed in browser
echo "<br>count : ".mysql_num_rows($r);//count of number of rows
$arr1=mysql_fetch_array($r);
?>
<table width="97%" border="0" >
<tr
<td width="11%"><div align="left"><strong>Description </strong></div></td>
</tr>
</table>
<textarea name="txt_Keywords" style="width:90%; height:90px"><?php echo $arr1[4]; ?></textarea>
And the output is nothing.
The query, when taken from the browser and put back in code along with values for variables we are getting an output.
$qu="SELECT DISTINCT bk.bookname,bk.author,bk.publisher,bk.edition,bk.description,lam.article_name,bk.keywords,bk.qtyinstock FROM lib_article_master lam, lib_book_cd_master bk WHERE bk.bookname='Java Complete Reference' AND bk.author='Martin D Leuthen' AND bk.publisher='ABS Publications' AND bk.article_id=lam.article_id";//here $arr[2],$arr[3],$arr[4] are replaced as per browser output
$r=QrySelect($qu);
echo " <br> ".$qu;//query is echoed in browser
echo "<br>count : ".mysql_num_rows($r);//count of number of rows
$arr1=mysql_fetch_array($r);
?>
<table width="97%" border="0" >
<tr
<td width="11%"><div align="left"><strong>Description </strong></div></td>
</tr>
</table>
<textarea name="txt_Keywords" style="width:90%; height:90px"><?php echo $arr1[4]; ?></textarea>
We are getting an output for the above code with correct number of rows from the the database.
Any help will be great.
You should use string concatenation to build your query, like
"SELECT * FROM table WHERE param = '" . $value . "'"
So, your query should look like:
$qu="SELECT DISTINCT bk.bookname,bk.author,bk.publisher,bk.edition,bk.description,lam.article_name,bk.keywords,bk.qtyinstock FROM lib_article_master lam, lib_book_cd_master bk WHERE bk.bookname='".$arr[2]."' AND bk.author='".$arr[3]."' AND bk.publisher='".$arr[4]."' AND bk.article_id=lam.article_id";
Also, don't forget to escape string variables with mysql_real_escape_string().
Got it at last... PHEW...
Just include 'TRIM()' and comparison problem got solved .Don't know still how it managed to work when code was pasted from browser but anyways its working.
giving the code below ...
$fr0=trim($arr[0], "");//'TRIMS' ALL UNWANTED SPACES FOR COMPARISON TO BE PERFECT
$fr1=trim($arr[1], "");
$fr2=trim($arr[2], "");
$fr3=trim($arr[3], "");
$bkr0=strtolower($fr0);//HERE EVERY SINGLE CHARCTER IS TURNED TO 'LOWER CASE' TO REMOVE ALL POSSIBLE WAYS OF ERRORS IN COMPARISON
$bkr1=strtolower($fr1);
$bkr2=strtolower($fr2);
$bkr3=strtolower($fr3);
//NOW COMPARISON FOR EACH VALUE IS DONE IN A WHILE LOOP BY 'mysql_fetch_row'
thank u all for your effort... it really meant a lot !