fetch_assoc doesn't show first row of results - php

Not sure what I did wrong. I'm aware that having two fetch_assoc removes the first result but I don't have such a thing.
$sql = "$getdb
WHERE $tablenames.$pricename LIKE 'm9%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo $tableformat;
while($row = $result->fetch_assoc()) {
$name = str_replace('m9', 'M9 Bayonet', $row['Name']);
include 'filename.php';
echo $dbtable;
}
My connect file:
$servername = "";
$username = "";
$dbname = "";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
require_once ('seo.php');
$dollar = '2.';
$euro = '1.9';
$tableformat = "<div class=\"CSSTableGenerator style=\"width:600px;height:150px;\"><table><tr><th>Name</th><th>Price</th><th><a class=\"tooltips\">Community<span>New !</span></a> </th><th>Cash Price</th><th>Trend </th><th>Picture </th></tr></div>";
$getdb = "SELECT utf.id, utf.PriceMin, utf.PriceMax, utf.Name, utf.Trend , community1s.price as com_price, utf.Name, utf.Trend
FROM utf
INNER JOIN (select id, avg(price) price from community1 group by id) as community1s
ON utf.id=community1s.id";
$tablenames = 'utf';
$pricename = 'Name';
$idrange = range(300,380);
What happens is, it fetches the first two column's fine and the rest of the row is not there and pushes the other results down one row, which messes up the data.
Here's an image to demonstrate:
http://imgur.com/CQdnycW
The seo.php file is just a SEO function.
Any ideas on what may be causing this issue?
EDIT:
My Output:
echo $tableformat;
while($row = $result->fetch_assoc()) {
$name = str_replace('m9', 'M9 Bayonet', $row['Name']);
include 'filename.php';
echo $dbtable;
EDIT: Solved it by moving my variables around. Marked as solved.

I found the issue. Some Variables that did the output were in a bad place. Rearranged them and now they are fine.

Your HTML is broken, and strange things happen in broken tables. $tableformat contains HTML that opens a <div> and a <table>, but then closes the <div> with the table still open.
Fix the broken HTML and you'll probably find that all is well

Related

Trying to compare a value from the database from the url after the?

I'm trying to get a value from the database and compare it with whatever id href was set. But nothing happens.
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "products";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$id = $row["id"];
echo <<<EOT
<br>
<form action='index.php?$id' method="POST">
<input type='submit' name="submit" value="more">
</form>
EOT;
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
while($row = $result->fetch_assoc()) {
if ($_SERVER["QUERY_STRING"] == $row) {
echo 'you clicked something from the database' . $id;
}
}
}
$conn->close();
?>
Trying to eventually get a value from the database then individually show a description if the more href is clicked.
your answer has a high time complexity you can easily make you
SQL query
SELECT id FROM items WHERE id = ?
and if the rows number is 0 this is mean there is no record with this id
you can check row's number from num_rows
You will never see "you clicked something from the database" message because you already fetched the result from your query in the first loop, check this question why-cant-i-loop-twice-on-mysqli-fetch-array-results
An option is to save the result in an array to use it later in your second loop
//your first loop
$savedRows = [];
while($row = $result->fetch_assoc()) {
$savedRows[] = $row;
//the rest of your code
}
// ......
// your second loop
if (isset($_POST['submit'])) {
foreach($savedRows as $row) {
if ($_SERVER["QUERY_STRING"] == $row['id']) {
echo 'you clicked something from the database ' . $id;
}
}
}
Also note that if this is your actual code, you need to make the closing identifier of your herodoc EOT; the first character on it's line, otherwise the rest of the file will be part of this string

What did i do wrong? Html is confusing itself

I'm making a page where you have to enter a text in a textbox and the click send, another page will save it.
Also, on the first page, the text that was stored previously in the database, has to load. This is the code that i've got:
<?php
$databaseid = 3;
$servername = "jog4fun.be.mysql";
$username = "jog4fun_be";
$password = "****";
$dbname = "jog4fun_be";
$gettitel1 = null;
$gettext1 = null;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Id,Titel,Tekst FROM Teksten";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row["Id"]== $databaseid ){
$gettitel1 = $row["Titel"];
$gettext1 = $row["Tekst"];
}
}
} else {
echo "0 results";
}
$conn->close();
$gettitel1 = strip_tags($gettitel1, '<br>');
$link1 = '<textarea id = "klein" rows="4" cols="50" name="titel3" form="usrform">' . $gettitel1 . '</textarea>';
$link2 = '<textarea id = "groot" rows="4" cols="50" name="text3" form="usrform">' . $gettext1 . '</textarea>';
echo $link1;
echo $link2;
?>
The problem is that it sends the text from textbox with name text3 as text1 with the post function. Can someone figure out what's wrong with it? I've been tying for an hour and i did not find it.
Thanks for your time and help,
Jonas
Simply here:
while($row = $result->fetch_assoc()) {
if ($row["Id"]== $databaseid ){
$gettitel1 = $row["Titel"];
$gettext1 = $row["Tekst"];
}
you overwrite the value of the two variables each time you iterate. So after this block of code you will keep stored the last values returned from the db.
YOu should add to your query a WHERE clause to identify the one and only record you need so you will fetch only the relevant data. Example:
$sql = "SELECT Id,Titel,Tekst FROM Teksten WHERE Id='1'";

Sending an array from PHP to javascript

In the PHP file can anyone help me directly making a for loop where I don't know the number of rows that are going to be selected.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";//database details
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$myarray = array();
$index = 0;
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$myarray[$index] = $row["firstname"];
$index++;
$myarray[$index] = $row["lastname"];
$index++;
$myarray[$index] = $row["email"];
$index++;
}
}
else
{
echo "0 results";
}
$conn->close();
?>
The Javascript code contains javascript of a search bar suggestion code and here i didn't mention the typeahead javascript file
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
$('#the-basics .typeahead').typeahead({
hint: true, //here i used typeahead js code though i didnt mentioned here
highlight: true,
minLength: 1
}, {
name: 'states',
source: substringMatcher(states)
});
You can simplify the PHP a little bit here when you read in the values as you dont need to increase the index:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";//database details
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);//making a connection
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$myarray = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$myarray[] =$row["firstname"];
$myarray[] =$row["lastname"];//storing in the array
$myarray[] =$row["email"];
}
} else {
echo "0 results";
}
$conn->close();
?>
You could echo in the results to the Javascript where you require them, echo($myarray[0]) for example.
Your Javascript may look something like this:
var matches = <?php echo($myarray[0]); ?>
There are 4 ways you can do to insert dynamic content to your javascript code.
Make the javascript inline to your PHP page. That is, putting your js code inside <script> tags
Make the dynamic js variables global and populate them in your php page. Your separate JS files will be able to read these global js variables.
If you want to have a separate file for JS, you have to generate it everytime (because you cant have PHP code in javascript. The browser cannot interpret it, and the server cannot interpret it)
If you want to force the server to interpret PHP code in JS files, add a handler so that .js is handler by the php interpreter (whether php module or php-cgi) see Clean links to PHP-generated JavaScript and CSS

IF VAR is in mySQL database then return that rows data as variable PHP

I've tried like twenty times and the closest I got was when I put in a variable stored in row 1 of the db and it returned the content the last row in the db. Any clarity would be extremely helpful. Thanks.
// Create connection
$coco = mysqli_connect($server, $user, $pass, $db);
// Check connection
if (!$coco) { die("Connection failed: " . mysqli_connect_error()); }
// Start SQL Query
$grabit = "SELECT title, number FROM the_one WHERE title = 'on' AND (number = 'two' OR number='0')";
$result = mysqli_query($coco, $grabit);
// What I need it to do
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$titleit = $row["title"];
$placeit = $row["number"];
$incoming = 'Help';
if ($titleit[$_REQUEST[$incoming]]){
$message = strip_tags(substr($placeit,0,140));
}
echo $message;
}
} else {
echo "not found";
}
mysqli_close($coco);
Put the input that you want to match into the WHERE clause of the query, rather than selecting everything and then testing it in PHP.
$incoming = mysqli_real_escape_string($coco, $_POST['Help']));
$grabit = "SELECT number FROM the_one WHERE title = '$incoming' AND number IN ('two', '0')";
$result = mysqli_query($coco, $grabit);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['number'];
}
} else {
echo "not found";
}
I think you need to add a break; in that if or I would assume it would go through each row in the database and set message if it matches the conditional. Unless you want the last entry that matches...if not you should debug:
if ($titleit[$_REQUEST[$incoming]]){
// set message
}
and see when it's getting set. That may not be the issue, but it's at least a performance thing and could explain getting the last entry
Have you tried print_r($row) to see the row or adding echos to the if/else to see what path it's taking?

Give value to Database by Pressing button

So i ran into some trouble not to long ago. As a student i am relativly new to programming and thus i often visit sites like these for help. My question is how can i add value to database by pressing a button. For me the problem here is that the button has a javavscript function to print. So in other words i want the button to have 2 functions, one that prints the page (which i already have) and one that adds value to the database. The purpose to adding the value to database is so people can see that its already been printed before.
So essentialy what i am asking for is how can i give a button 2 functions (one which is Javascript) and show people that the button is used(in this case, that it has been printed). All help will be appreciated very much.
My code is as following:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query("SELECT * FROM orders");
// Count the returned rows
if($resultSet->num_rows != 0){
// Turn the results into an Array
while($rows = $resultSet->fetch_assoc())
{
$id = $rows['id'];
$naam = $rows['naam'];
$achternaam = $rows['achternaam'];
$email = $rows['email'];
$telefoon = $rows['telefoon'];
$bestelling = $rows['bestelling'];
echo "<p>Name: $naam $achternaam<br />Email: $email<br />Telefoon: $telefoon<br /> Bestelling: $bestelling<br /> <a href='delete.php?del=$id'>Delete</a> <input type='button' onclick='window.print()' value='Print Table' /> </p>";
}
// Display the results
}else{
echo "Geen bestellingen";
}
?>
This would aquire 2 tasks:
Is that you bind a function to the click handler of the button.
Although it is bad practice to use function calls directly, in your case this would be that you replace the window.print() by a custom javascript function.
In that javascript function, you execute the window.print() again, where-after you do the next step in the logic: sending data to PHP.
With ajax you can archieve this.
With a parameter in the function you can pass what the ID of the current row is, which need to be passed to PHP.
You need to create another PHP script, that will be called by tje AJAX script.
In that PHP script you will do the required updates to the database.
Ok There is a lot of ways you can do it but here is how i would do it :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query("SELECT * FROM orders");
// Count the returned rows
if($resultSet->num_rows != 0){
// Turn the results into an Array
while($rows = $resultSet->fetch_assoc())
{
$id = $rows['id'];
$naam = $rows['naam'];
$achternaam = $rows['achternaam'];
$email = $rows['email'];
$telefoon = $rows['telefoon'];
$bestelling = $rows['bestelling'];
//first you call a custom javascript function after the 'onclick'. I believe you'll have to pass a variable as an argument (like $id).
echo "<p>Name: $naam $achternaam<br />Email: $email<br />Telefoon: $telefoon<br /> Bestelling: $bestelling<br /> <a href='delete.php?del=$id'>Delete</a> <input type='button' onclick='print_table($id)' value='Print Table' /> </p>";
}
// Display the results
}else{
echo "Geen bestellingen";
}
?>
Then you write this function in the header of your page
<script>
function print_table(id)
{
//print your document
window.print();
//send your data
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","http://www.domaine.com/directories/printed_table.php?id=" + id;
xmlhttp.send();
}
</script>
Then you write your file printed_table.php where you store 1 if printed or 0 if not printed. I don't understand german so i don't know where you store your printed variable but it goes like this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$id = $_GET['id'];
$resultSet = $conn->query("UPDATE `orders` SET `printed` = 1 WHERE `id` = `$id`");
?>
This should work. Just be careful and check the $_GET['id'] before to use it for security purposes. like you can use the php function is_int(). Depending of the security level you need you might want to secure this code a little more.

Categories