Database only fetching first variable - php

This php is populated by a form posting variables to it. Once it has the car model it should be collecting data from the database and storing each variable for use further down the code. This is used alongside another database so I would rather populate each var list before moving ahead.
The problem is, the database is only collecting the first variable and none of the following variables. How can I call all variables and hold them there for use in the html below.
eg. The client selects the car model, submits and the form sends the model to this code where the database should collect more information about the car for use in a automatically generated PDF brochure.
Thanks for your help!!
//database, table CARS and store variables
$conn = mysql_connect("localhost", "blah", "blah");
mysql_select_db("car_db", $conn);
$sql = "SELECT * FROM cars WHERE modelname = '$carmodel'" or die(mysql_error());
$rs_result = mysql_query ($sql, $conn);
while ($row = mysql_fetch_assoc($rs_result))
//create variables from database entry
$dbbrand = $row['brandname'];
$dbseries = $row['series'];
$dbprice = $row['price'];
$dbseats = $row['seats'];
$dbtype = $row['type'];
$dbcolor = $row['color'];
// -------------------- HTML CONTENT -------------------- //
$html = "
<body>
<!--Print Wrap Start-->
<div id=\"content\">
<!--Header with logo-->
<div id=\"div-head\"><div id=\"div-head\"><span class=\"important\">". $dbbrand ."</span></div></div>
<!--start relative container-->
<div id=\"div-1\"><span class=\"important\">". $dbseries ."</span>

Assuming your syntax is copied as stated above, you need to put braces "{" and "}" around your variable assignments.
$sql = "SELECT * FROM cars WHERE modelname = '$carmodel'" or die(mysql_error());
$rs_result = mysql_query ($sql, $conn);
while ($row = mysql_fetch_assoc($rs_result)) { <----- here
//create variables from database entry
$dbbrand = $row['brandname'];
$dbseries = $row['series'];
$dbprice = $row['price'];
$dbseats = $row['seats'];
$dbtype = $row['type'];
$dbcolor = $row['color'];
} <---- here

The problem is here
while ($row = mysql_fetch_assoc($rs_result))
//create variables from database entry
$dbbrand = $row['brandname'];
That code assigns a record from the result set into the $row variable, which in only used to assign the current value into the $dbbrand variable below the loop.
The while loop only controls one line of code and that is $dbbrand = $row['brandname'];. You need to wrap all the relevant lines of code below as a apart of the the while loop. Below I will demonstrate and correct for the other logical error in your code.
$data = array();
int a=0;
while ($row = mysql_fetch_assoc($rs_result)) {
//create variables from database entry
$data[a]['dbbrand'] = $row['brandname'];
$data[a]['dbseries'] = $row['series'];
$data[a]['dbprice'] = $row['price'];
$data[a]['dbseats'] = $row['seats'];
$data[a]['dbtype'] = $row['type'];
$data[a]['dbcolor'] = $row['color'];
$a++;
}
If you want all values returned by the query, the adjustment to your code above will suffice.

Related

PHP: update variables on while statements

I am new to the PHP world! Currently practicing MySQL and PHP alone
I want to update my <p> content when my query is completed. But seems like my $name only shows the previous value:
$query = $_GET['query'];
$stmt = $conn->prepare("SELECT * FROM wordList WHERE word = '$query'");
$name = ''; // my variable
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$name == $row['word']; // not working
}
And I am not getting the actual data I want in my HTML:
<p>My name is: <?php echo $name; ?></p>
But getting:
My name is:
Thanks
Try using only one equal to symbol = instead of ==.
$name = $row['word'];

Why does my php returns one value (one row) from mysql?

I have a php file that should returns value from mysql, her is my php file:
<?php
$host = "localhost"; // Host name
$username = "UserName"; // Mysql username
$password = "PassWord"; // Mysql password
$db_name = "DbName"; // Database name
$tbl_name = "Notes"; // Table name
// Connect to server and select databse.
mysql_connect($host, $username, $password)or die("cannot connect");
mysql_select_db($db_name)or die("cannot select DB");
// To protect MySQL injection (more detail about MySQL injection)
$mytitle = $_REQUEST['title'];
$mytitle = stripslashes($mytitle);
$mytitle = mysql_real_escape_string($mytitle);
$sql="SELECT * FROM $tbl_name WHERE title = '$mytitle'";
$result = mysql_query($sql);
// Mysql_num_row is counting table row
$count = mysql_num_rows($result);
$count = 0;
$items;
while($row = mysql_fetch_array($result)) {
$item['userName'] = $row['userName'];
$item['title'] = $row['title'];
$item['comments'] = $row['comments'];
$item['commentsTime'] = $row['commentsTime'];
$item['commentsDate'] = $row['commentsDate'];
$items[$count] = $item;
}
echo json_encode($items);
?>
The file does return only one value when I run the code from my browser, I access the file via URL (http://MyWeb.com/ReadNotesByTitle.php?title=titleName).
Can any one tell me what is the wrong with my code?
Thanks
You have missed $count++; inside while loop
You never increment $count; it always has the value 0. So the second item will overwrite the first, the third will overwrite the second, and so on. Ultimately, you will only return the last row fetched from the database.
Increment $count at the end of the loop to solve the problem:
$items[$count] = $item;
$count++;
}
Alternatively, you can append an element to an array without keeping track of the count. Remove the $count variable entirely and change your array assignment to:
$items[] = $item;
While I see this has already been answered I thought I should note you are making your code more complicated than it has to be. You're entire while loop can be summarized as below and will give your desired results
while($row = mysql_fetch_array($result)) {
$items[] = $row;
}

Multiple PHP dynamic variables displaying other dynamic variable values

I am generating dynamic variables like so:
$testPMA = '';
$result = mysql_query("SELECT * FROM site_pma") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
${$testPMA.$row['id']} = $row['value'];
}
$testLocation = '';
$result = mysql_query("SELECT * FROM site_location") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
${$testLocation.$row['id']} = $row['value'];
}
then I try displaying them like so:
if(isset(${$testPMA.$row_bom_lines['pma']})) echo ${$testPMA.$row_bom_lines['pma']};
The first one returns correctly. The next column and any after always take their id number for the dynamic variable, but only generate PMA. They never update to show Location or any other one I have created. I even tried mysql_free_result($result); after each one. How do I get the dynamic variable to display each of their own vs displaying the same table information for each column, just with an updated id number?

Variable URL PHP and MySQL

Just trying to pass a variable on URL so that when echoed I can click on it and open it's own content based on the database record. Right now this one shows all the records from database but what I was trying to do was pass a URL so each blog IDs will have it's own URL and when clicked on it will open the individual entries rather than all the entries.
Edited Now I'm able to show rows of entries with IDs where 'IDs' has URL variable at the end. Do I need to create another query to echo the individual entry on my mini blog?
<?
$db = // connection to db and authentication to connecting to db;
#$postID = $_GET['postID']; // I'm thinking to use a $_GET global variable to work with URL variable
$command = "select * from $table_name"; // I'm thinking to add the Id here or something or create another query to echo the linked URL 'viewblog.php?postID=$data->blogID'
$result = $db->query($command);
while ($data = $result->fetch_object()) {
echo "<TR><TD><a href='viewblog.php?postID=$data->blogID'>".$data->blogID."</a></TD>";
echo "<TD>".$data->author."</TD>";
echo "<TD>".$data->date."</TD>";
echo "<TD>".$data->entry."</TD></TR>\n";
}
$result->free();
$db->close;
Why this script is giving all entries?
Because the final query that is being sent to the database is something like
select * from TABLE_NAME
which will return all entries since your are using the asterix * after SELECT
What you are asking for can be obtained if the executed final query contains the "blogID" before retrieving the results and start fetching them.
http://www.w3schools.com/sql/sql_where.asp
You should also use the fetched or post ID in the echoed result (so that when clicked, each blog has its own id in the link).
It could be something like this
$postID = $_GET['postID'];
//Add filtering by id to select statement
$command = "select * from '$table_name' obj WHERE obj.blogID = '$postID'";
$result = $db->query($command);
while($data = $result->fetch_assoc()){
$data['blogID'] = $postID;
//Add ID to echoed link
echo "<TR><TD> Some Blog (ID: ".$data['blogID'].") </TD>";
echo "<TD>".$data['author']."</TD>";
echo "<TD>".$data['date']."</TD>";
echo "<TD>".$data['entry']."</TD></TR>\n";
}
WATCH OUT for security issues regarding this code. You should use a safer way to do this. I'm only explaining the results.
As for Auto Increment, it can be initiated when you first created the table. This is for when you INSERT a new row into the database. When you use Auto Increment, you don't have to give an ID manually.
http://www.w3schools.com/sql/sql_autoincrement.asp
Notice : The HTML BR ELEMENT should not be used inside TABLE structures.
Hope it helps.
You could create some function like this for returning single post based on url
function single_blog($Post_id){
$sql = "SELECT * FROM your_table WHERE post_id = ? LIMIT 1";
$stmt = $this->db->prepare($sql);
$stmt->execute(array($Post_id);
return $stmt->fetch();
}
You are selecting all entries from your table. Use the following:
$db = // connection to db and authentication to connecting to db;
$postID = $_GET['postID']; // ??
$db->real_escape_string(trim($postID));
$command = "select * from $table_name WHERE `postID`=$postID";
$result = $db->query($command);
// Ensure results before outputting
if ($result->num_rows) while($data = $result->fetch_assoc()){
$data['blogID'] = $postID;
echo "<TR><TD><a href='viewblog.php?postID='>".$data['blogID']."</a> </TD>"; //??
echo "<TD>".$data['author']."</TD>";
echo "<TD>".$data['date']."<BR></TD>";
echo "<TD>".$data['entry']."</TD></TR>\n";
} else echo "No entry found!";
$result->free();
$db->close;
<?php
//$db connect to database
// Entry form sanitation of $_POST
// Insert PHP file to MySQL
// View all blog posts
$postID = $_GET['postID']; // I guess I should sanitize this as well
if (!empty($postID)) {
$command = "select * from $table_name where blogID = $postID";
$result = $db->query($command);
while ($data = $result->fetch_object()) {
$postID = $data->blogID;
echo "<TR><TD>".$postID."</TD>";
echo "<TD>".$data->author."</TD>";
echo "<TD>".$data->date."</TD>";
echo "<TD>".$data->entry."</TD></TR>\n";
}
$result->free();
}
else {
$command = "select * from $table_name";
$result = $db->query($command);
while ($data = $result->fetch_object()) {
$postID = $data->blogID;
echo "<TR><TD><a href='viewblog.php?postID=$postID'>".$postID."</a></TD>";
echo "<TD>".$data->author."</TD>";
echo "<TD>".$data->date."</TD>";
echo "<TD>".$data->entry."</TD></TR>\n";
}
$result->free();
}
$db->close;
?>

PHP loop increment

I have a PHP loop generating a dataset for a chart. It queries two fields I have in a database table.
<?php
$server = "myserver:1234";
$user="dbuser";
$password="userpass";
$database = "dbname";
$connection = mysql_connect($server,$user,$password);
$db = mysql_select_db($database,$connection);
$query = "SELECT X, Y FROM dbtable";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$dataset1[] = array($row['X'],$row['Y']);
}
$final = json_encode($dataset1,JSON_NUMERIC_CHECK);
?>
Currently data in X is meaningless (it's actually an ID column), and a number increment of 1 starting at 1 will be more useful. This is because I only want to plot a line chart, where X values are fixed. ID would be fine but the values put distracting axis labels on my chart.
How can I use PHP to generate this instead of the database select that I currently have?
Many thanks:)
Declare a variable outside your loop and increment it on each iteration:
$i = 1;
while($row = mysql_fetch_assoc($result))
{
$dataset1[] = array($i, $row['Y']);
$i++;
}

Categories