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 !
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 ) { … }
This is the HTML/PHP , I am using to display some data.
<body>
<section>
<h1>Facebook Search</h1>
<!-- TABLE CONSTRUCTION-->
<table>
<tr>
<th>Comment</th>
<th>Comment Made By</th>
<th>Commentor's Profile Link</th>
<th>Comment ID</th>
<th>Post ID</th>
</tr>
<!-- PHP CODE TO FETCH DATA FROM ROWS-->
<?php // LOOP TILL END OF DATA
while($rows=$result->fetch_assoc())
{
?>
<tr>
<!--FETCHING DATA FROM EACH
ROW OF EVERY COLUMN-->
<td><?php echo $rows['comtext'];?></td>
<td><?php echo $rows['comby'];?></td>
<td><?php echo $rows['compro'];?></td>
<td><?php echo $rows['commentid'];?></td>
<td><?php echo $rows['postid'];?></td>
</tr>
<?php
}
?>
</table>
</section>
</body>
</html>
and I am getting the data like this from the db.
$sql = "SELECT comments.*, posts.postid FROM comments JOIN posts USING(postid)";
$result = $mysqli->query($sql);
$mysqli->close();
This outputs a single table with all the data. My question is , is there a way to break the single table into tables when the value of postid changes? It goes like..is 1 for x number of rows, then 2 for x number of rows and so on. I wanted to have a little break between those tables.
is there a way to break the single table into tables when the value of postid changes
You should stop using "SELECT *", it's inefficient and makes code difficult to maintain. While we're talking about style here, you swap back and forth between PHP and inline HTML which also impacts the readability of your code.
As to your question...
You need to ensure that the output of your query is sorted by postid - or you're going to get a lot of tables.
Use a state variable to track the postid from the previous iteration of the loop.
$prev=0;
while($rows=$result->fetch_assoc()) {
if ($rows['postid']!=$prev) {
close_table();
open_table();
$prev=$rows['postid'];
}
output_row($rows);
}
close_table();
The problem with this is that each iteration of the expects that you've already written <table> to the output stream - including the first iteration. You could do this before the loop - but you'll end up with an empty table at the top of the page. You could add another state variable to track whether you have opened a table tag yet. Personally, I'd go with making inferences from the value of the existing state variable:
$prev=0;
while($rows=$result->fetch_assoc()) {
if ($rows['postid']!=$prev) {
$prev || close_table();
open_table();
$prev=$rows['postid'];
}
output_row($rows);
}
close_table();
(the || is a quick way of writing if (not(condition)) do something() )
Note that unless you fix the size of the columns, then each table will be independently sized to fit the data that resides within it.
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"]."'"
I have downloaded a shopping cart for my site,
It has a PHP file to fill out the basket. the basket will show added items in rows, here is the code :
<?php
define('INCLUDE_CHECK',1);
require "XXXXX/XXXXX.php";
if(!$_POST['img']) die("There is no such product!");
$img=mysql_real_escape_string(end(explode('/',$_POST['img'])));
$row=mysql_fetch_assoc(mysql_query("SELECT * FROM XXXXXX WHERE img='".$img."'"));
$prsize=mysql_fetch_assoc(mysql_query("SELECT * FROM BBBBBB WHERE id='".$row['id']."'"));
echo '{status:1,id:'.$row['id'].',price:'.$row['price'].',txt:\'\
\
<table width="100%" id="table_'.$row['id'].'">\
<tr>\
<td width="60%">'.$row['name'].'</td>\
<td width="10%">$'.$row['price'].'</td>\
<td width="15%"><select name="'.$row['id'].'_cnt" id="'.$row['id'].'_cnt" onchange="change('.$row['id'].');">\
<option value="1">1</option>\
<option value="2">2</option>\
<option value="3">3</option></slect>\
\
</td>\
<td width="15%"><select name="'.$prsize['id'].'_cnt" id="'.$prsize['id'].'_cnt" onchange="change('.$prsize['id'].');">\
I need to put this
while($item = mysqli_fetch_array($result))
{
here to make a dynamic select menu for the size
<option value="'.$prsize['id'].'">'.$prsize['id'].'</option>\
end while
}
\
</td>\
<td width="15%">remove</td>\
</tr>\
</table>\'}';
?>
but I couldn't figure it out how to put the PHP while in there, I have tried to use "" or '' but no luck.
How should I quote the PHP while inside this HTML code?
Thanks
Maybe something like this:
$options = "";
while($item = mysqli_fetch_array($result))
$options .= "<option value=\"$item[id]\">$item[id]</option>\\\n";
and then just use it
echo '{status:1,id:'.$row['id'].',price:'.$row['price'].',txt:\'\
\
<table width="100%" id="table_'.$row['id'].'">\
<tr>\
<td width="60%">'.$row['name'].'</td>\
<td width="10%">$'.$row['price'].'</td>\
<td width="15%"><select name="'.$row['id'].'_cnt" id="'.$row['id'].'_cnt" onchange="change('.$row['id'].');">\
'.$option.'</select>\
...
Or you can simply break your echo in two and put your loop between the calls:
echo '{status:1,id:'.$row['id'].',price:'.$row['price'].',txt:\'\
\
<table width="100%" id="table_'.$row['id'].'">\
<tr>\
<td width="60%">'.$row['name'].'</td>\
<td width="10%">$'.$row['price'].'</td>\
<td width="15%"><select name="'.$row['id'].'_cnt" id="'.$row['id'].'_cnt" onchange="change('.$row['id'].');">\
';
while($item = mysqli_fetch_array($result))
echo "<option value=\"$item[id]\">$item[id]</option>\\\n";
echo '</select>\
\
</td>\
...
Btw, your </select> is missing one "e" (it says </slect>).
My eyes bleed whenever I see PHP and HTML mixed together like that.
There are 6 things that I'd like to highlight in your code:
1) It seems to me like you're trying to build some kind of JSON string with your php, here's my evidence:
echo '{status:1, id:'.$row['id'].'} //The rest of your code
I'd like to make you aware of the command json_encode that transforms a php array into JSON-like string that can be read by JavaScript (just to name one) and manipulated in whatever way you want.
This is the way you use it:
$myJSONobject = json_encode($myarray)
2) mysql_ functions are deprecated
I don't know how many times I have to type this per day, but they are, do not use them anymore. Even if you're reading an outdated tutorial or written by a bad programmer that still use mysql_* functions in 2013.
Deprecated means that those functions can go away at any point in time, if your server updates to a PHP version that no longer has deprecated functions, all your code will be broken and you're going to wonder why.
From now on, you have to use mysqli or PDO
4) Your SQL is vulnerable to SQL Injection
$prsize=mysql_fetch_assoc(mysql_query("SELECT * FROM BBBBBB WHERE id='".$row['id']."'"));
I'm pretty sure you're writing statements like that all over your program, I'm also pretty sure that at some point you're accepting input from the user and making a SQL query like that.
If a malicious user decides to enter 1 OR 1=1 that user is going to execute a SQL statement that he is not supposed to execute, something like:
SELECT * FROM BBBBBB WHERE id = 1 OR 1=1
That could have been prevented if instead of using mysql_* functions you would have used mysqli or PDO
Because those libraries come with prepared statements A prepared statements forces the SQL engine to understand your query BEFORE any data is passed to it. Therefore, if a malicious user tries the good ol' OR 1 = 1, it won't matter because the SQL engine will handle it as any other string, and not as a command.
5) Your code is an ugly mess.
Even if this comment doesn't look like constructive criticism, it actually is, read on to find out why.
The way you're coding this program, makes it hard to maintain. You shouldn't be mixing PHP and HTML together the way you're doing it.
Most of the time you should only echo or return raw data.
If you're markup code, the vast majority of time, you're doing it wrong.
6) Do not use onclick` in HTML anymore, it's TERRIBLE practice. Use Event Listeners instead
Click me
<script type="text/javascript">
var link = document.getElementById("test").
link.addEventListener("click", function() {
link.innerHTML = "Do not click me anymore please";
});
</script>
Back to your question, there's no need to write that mess if you want to mix PHP and HTML, I'm going to show you a cleaner way to output this:
$prsize=mysql_fetch_assoc(mysql_query("SELECT * FROM BBBBBB WHERE id='".$row['id']."'"));?>
{
status:1,
id:<?=$row['id']=?>,
price:<?=$row['price']?>,
txt:
<table width="100%" id="table_<?=$row['id']?>">
<tr>
<td width="60%"><?=$row['name']?></td>
<td width="10%">$<?=$row['price']?></td>
<td width="15%">
<select name="<?=$row['id']?>_cnt" id="<?=$row['id']?>_cnt" onchange="change(<?=$row['id']?>);">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
<td width="15%">
<select name="<?=prsize['id']?>_cnt" id="<?=$prsize['id']?>_cnt" onchange="change(<?=$prsize['id']?>);">
<?php while($item = mysqli_fetch_array($result)): ?>
<option value="<?=$prsize['id']?>"><?=$prsize['id']?></option>
<?php endwhile; ?>
</td>
<td width="15%">
remove
</td>
</tr>
</table>
}
Hope this helps, then again... if you're creating JSON... use JSON_ENCODE
$SQL = "SELECT * from xxx WHERE img = '".mysql_real_escape_string($img)."'";
$result = mysql_query( $SQL );
while( $item = mysql_fetch_array( $result ) ) {
echo '<option value="'.$item['id'].'">'.$item['id'].'</option>';
}
1st Page that links to the 2nd
<td>More Detail</td>
2nd Page
$toyId=$_GET["toyInfo"];
$question = "SELECT * FROM toy, toyscountry, toysmedia, alltoyscategory WHERE toy_id= '$toyId' AND toy.toy_country = toyscountry.tCou_id
AND toy.toy_id = toysmedia.tMedia_toyId
AND toy.toy_id=alltoyscategory.allToysCat_toyId";
$reply = mysqli_query($dbConnection, $question);
echo $question;
ERROR FOUND AFTER ECHO
Notice: Undefined index: toyInfo in C:\Program Files (x86)\EasyPHP-12.0\www\CA1\moreToysDetail.php on line 5
SELECT * FROM toy, toyscountry, toysmedia, alltoyscategory WHERE toy_id= AND toy.toy_country = toyscountry.tCou_id AND toy.toy_id = toysmedia.tMedia_toyId AND toy.toy_id=alltoyscategory.allToysCat_toyId
They couldnt detect toyInfo :( Any kind souls that can help? Greatly appreaciated, I need to hand in my assignment in a few hours time >.<
I spot 3 things that might be wrong with your code:
first:
<td>More Detail</td>
should look like
<td>More Detail</td>
This assumes your php is configured to accept the shorthand <? in stead of the default <?php
second:
is your toy id in the databse not stored as an integer? It pobably should, as it is best practice for an id. This means you don't need the single quotes in you SQL statement:
... WHERE toy_id= $toyId AND ...
third:
Your final line of code does not make much sense. You are echoing the SQL statement. I believe you'ld want to echo the reply. Have a look here http://www.php.net/manual/en/class.mysqli-result.php to find out how to do this, as the reply currently holds an object that you can not just use echo on to display the data.
Your code has a unexpected "=" so that must have been the problem, you also needed to echo $currentToy["toy_id"];
<td>More Detail</td>