Hi there I have a website which takes in a Car brand and generates a Car Id result which corresponds to a database. Although there are many solutions available for storing a sql query result to a variable but in this case it does not seem to work.
I have already tried the sql statement in the database and it works with 1 result output which is right.
<?php
session_start();
include "dbconn.php";
$carcat = $_SESSION['selectedcarcat'];
$carbrand = $_POST['carbrand'];
$userid = $_SESSION['loginid'];
$username = $_SESSION['loginname'];
$startdate = $_POST['date1'];
$enddate = $_POST['date2'];
$pick = $_POST['pickuploc'];
$return = $_POST['returnloc'];
$calqty = 0;
$selcaridsql = "SELECT carid FROM cars WHERE brand='$carbrand' ";
$caridresult = $dbcnx->query($selcaridsql);
$caridrow = mysql_fetch_object($caridresult);
$carid = $caridrow['carid'];
if (!$caridresult)
{
$errmessage = "Your carid select query failed.";
echo "<script type='text/javascript'>alert('$errmessage');</script>";
}
echo '<br>Debug 1 ';
echo '<br>The selected qty is '
.$qtyresult1.'<br />';
echo '<br>The calculated qty is '
.$calqty.'<br />';
echo '<br>The content carid is '
.$carid.'<br />';
echo '<br>The content userid is '
.$userid.'<br />';
echo '<br>The content start is '
.$startdate.'<br />';
echo '<br>The content end is '
.$enddate.'<br />';
echo '<br>The content pick is '
.$pick.'<br />';
echo '<br>The content return is '
.$return.'<br />';
echo '<br>The content carbrand is '
.$carbrand.'<br />';
?>
The error occurs with a blank result shown at the "Content carid is". After going through the forums it seems that the variable $carid has no value which I may have inferred wrongly.
The echo results:
Debug 1
The selected qty is
The calculated qty is 0
The content carid is
The content userid is
The content start is 2016-10-28
The content end is 2016-10-29
The content pick is jurong
The content return is bishan
The content carbrand is Honda
Apparently after using var_dump to debug the problem as stated by Chris, the problem was narrowed down to the NULL value that was collected by the mysql_fetch_object($caridresult);. As the DB connection utilizes #$dbcnx = new mysqli('localhost','values','values','values'); the DB class is wrong for retrieving the array values. Therefore the solution would be mysqli_fetch_array.
These codes might be helpful for those trying the debug:
<?php // register.php
session_start();
include "dbconn.php";
$carcat = $_SESSION['selectedcarcat'];
$carbrand = $_POST['carbrand'];
$userid = $_SESSION['loginid'];
$username = $_SESSION['loginname'];
$startdate = $_POST['date1'];
$enddate = $_POST['date2'];
$pick = $_POST['pickuploc'];
$return = $_POST['returnloc'];
$calqty = 0;
$selcaridsql = "SELECT carid FROM cars WHERE brand='$carbrand' ";
echo $selcaridsql."<br>";
$caridresult = $dbcnx->query($selcaridsql);
echo "<br>".var_dump($caridresult);
if ($caridresult->num_rows >0 )
{
// if they are in the database register the user id
echo '<br>Hello more than 1 <br>';
}
else
{
echo '<br>Hello less than 1 <br>';
}
$caridrow = mysqli_fetch_array($caridresult);
echo var_dump($caridrow)."<br>";
$carid = $caridrow['carid'];
echo var_dump($carid)."<br>";
if (!$caridresult)
{
$errmessage = "Your carid select query failed.";
echo "<script type='text/javascript'>alert('$errmessage');</script>";
}
echo '<br>Debug 1 ';
echo '<br>The selected qty is '
.$qtyresult1.'<br />';
echo '<br>The calculated qty is '
.$calqty.'<br />';
echo '<br>The content carid is '
.$carid.'<br />';
echo '<br>The content userid is '
.$userid.'<br />';
echo '<br>The content start is '
.$startdate.'<br />';
echo '<br>The content end is '
.$enddate.'<br />';
echo '<br>The content pick is '
.$pick.'<br />';
echo '<br>The content return is '
.$return.'<br />';
echo '<br>The content carbrand is '
.$carbrand.'<br />';
?>
Special Thanks to Chris for helping to find the error!
I do not have the ability to test this right now.
However, you have confirmed that $carid has no value (is null).
And you have confirmed the SQL statement returns correct values when run against the database. Therefore, a likely problem is with the query you are sending to the database with your code.
your query:
$selcaridsql = "SELECT carid FROM cars WHERE brand='$carbrand' ";
my suggestion to fix your query:
$selcaridsql = "SELECT carid FROM cars WHERE brand='" + $carbrand + "'";
You could be sending the string literal "$carbrand" and not know it unless you printed out that SQL statement to check.
Have you tried that?
Also, please check the values of all your $_POST to be sure they are what you think they are. That is very important for security as well.
Get to those println statements and let me know what you find :-).
Print everything out and make sure your values are what you expect.
I'm 99% sure that's where the problem is.
Related
So, I'm trying to use PHP in order to query an sqlite database, I have no problem with the connection or with the query itself, however, I don't know what I could do in order to display the data in a clean way, or even put it inside an HTML table. The code I'm working with right now is:
<?PHP
$connection = new SQLite3('my_db.db');
if($connection){
echo "Connected\n";
}
$results = $connection->query('SELECT * FROM Meter1');
while($row=$results->fetchArray()){
var_dump($row);
}
?>
After you have done a $row = fetchArray() the variable $row is a array containing the data returned from your query in the form of an Array. If you add SQLITE3_ASSOC it will be an Associative Array where the keys are the names of the database columns.
So lets assume your table has the columns id, name, dob then this would be how you get to that column data
<?php
$connection = new SQLite3('my_db.db');
if($connection){
echo "Connected\n";
}
$results = $connection->query('SELECT * FROM Meter1');
while($row=$results->fetchArray(SQLITE3_ASSOC)){
echo 'id = ' . $row['id'] . '<br>';
echo 'name = ' . $row['name'] . '<br>';
echo 'Date of Birth = ' . $row['dob'] . '<br>';
}
?>
So if you want the data in a table its just a case of wrapping the HTML around that while loop like this
echo '<table>';
echo '<tr><td>id</td><td>name</td><td>Date of Birth</td></tr>';
while($row=$results->fetchArray(SQLITE3_ASSOC)){
echo '<tr>';
echo "<td>$row[id]</td><td>$row[name]</td><td>$row[dob]</td>";
echo '</tr>';
}
echo '</table>';
I have to output a series of random images previously saved inside a DB.
At the moment of the output, instead print a picture, the code print a strange string (meaby dumpfile?):
(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢¢’ú~ü±®æIüa¤Äû[SÓÕºàܦ'$·›ØÒ¢°o>)xvÀŸ7ZÓדþULünð®ì.±„ðFíŸÉj=¬íìæöLꨮ6ã㦇êW8b³|Ä⪟ÚL-…Óu¦ÇRmÕ#ÿǪ^"’ûH¯cQô;Ê+ÏeøýC£Ý:ó÷çHÏåTnh[¿»ÐãRz/Ïýò¦£ë”—_ÌW©Øõ +Écý µIæùltuà¯Údfúgg_´ÿh1ÿMÓ?O&à¹ü™ùÒXÊ/¯æSÂÔ]H¢¼õi £mœÝ[°ë¹Pãòlþ•¥iñïÂwmµudVÎèd~;qúÖ‘ÄR{IèT_e…‹iñ#Ã÷»|½kKfnŠnQXþæµî£»ŒFßµ¦´ÖëöÏôpND;W?ÝL…V9à'5ÏSK–GE<,çhŸNîWϺoÇu·\ëW–¹É˜Í ¯ÕÖRºgß½^“Äñ_D¬ºÕ×™ÈÿM‘”þ$°üy¬þ¹…}R]Ot¨n5;{?õ×Åþû…þuóî¦öîònû»,ñ³Ãþ†¨ËtÖŸô €ò“üÿLGþ5/ýÒヿSè¼s¢Û¶×Ö4µoF»ŒZ‚‰:°ùµK^ÿp—þUàªI(eä{z ³œÁyú`U9V5>c¤…T‚7ØÉz®EGץصƒ]Yï|n𼃪+Ù ‘赿41þ«í·î#WÿBÅxŒªmÿH½ó±)_ å³O·˜Jî±ÚÝ6:eb…‰õû£ô¨xéô±_S‡™ì§ãréÚ§# 7’3ÿ‘*´¿óˆ´é™²Ïqÿ"kËžÂiUzÛ«rƒóÀþ•Nh$óTIçÎPmn§Àú€ê?J—Œ¨RÂÀõi~:ÜÿË=Y¼oT5Vããn´Ì='O…›§uŸýšòñ£GqüVJü|Óϳ1Ç¥8h&7GjÁ;maíÇ9ÅfñU{”°Ô»_yè—µhŸC·œ€ÿÌ·ôª³üsÔ¤ÿW¨i¬Ýˆ+üëˆ&ÞÏ8¸’>p°R3þî)ñ[óñ%ño{–eÿЇYªú—õzk¡ÖIñ{W½UªH¥€ÿWj}ú*§7Å#îó5«ÍÃÑZ1ü¿•ssè6¨Û¦U™¾ñÖ }2ÇóÅ8-¸m¶²dÿN¨ÓŒÔ:•V5NšÙÒüGšBÊ××ó?ç´Ÿ úV|þ&þЙn$QÔõÇJlSB]•¡‡o\;·õëS‰]¢†=¸àˆœ¨={ŸåëÞ£ß{²’ŠÙ÷¬Ï»ì3Éè¼ûöÜjIDiá¤Ä«Û|hÌ?J-æ˜Ûå)çæ…rãüõ©Ròt’Bœÿ¬‰8úýj,Ê¿b8šêÕwCco©þ€h¼Ôµgý\kï'ò;³ú~U$º
My code:
<?php
include_once('conn.php');
$n="SELECT COUNT('id_product')
FROM 'products'";
$value=mysql_query($n);
do
{
$selectionASC='SELECT id_product
FROM products
ORDER BY id_product ASC
LIMIT 1';
$selectionDESC='SELECT id_product
FROM products
ORDER BY id_product DESC
LIMIT 1';
$ASC=mysql_query($selectionASC)
or die ('Impossible execute the query <br />').mysql_error();
$DESC=mysql_query($selectionDESC)
or die ('Impossible execute the query <br />').mysql_error();
//____________________________________________________________________
$ASC = mysql_num_rows($ASC);
$DESC = mysql_num_rows($DESC);
$rand_n=rand(($ASC-1),($DESC+1));
//____________________________________________________________________
$selected='SELECT id_product,name, price, img
FROM products
WHERE id_product='.$rand_n;
$selected = mysql_query($selected);
//____________________________________________________________________
while($row=mysql_fetch_row($selected))
{
echo "Product'id:  "; echo $row[0];
echo '<br />';
echo "Name:  "; echo $row[1];
echo '<br />';
echo "Price::  "; echo $row[2];
echo '<br />';
echo "Immage: <img src='images/".$row['3']."'alt='Image'>";
echo '<hr> <br />';
$value--;
}
}
while ($value==0)
?>
The rest of the output is coherent with the code. Anyone know why it happen? And how to fix it? Thanks!
You cannot output image like what you did , first of things
when you fetch image from db .
for example if my image filed stored in img field i will call it like this
$id=$_GET['id'];
$query = mysql_query("select * from img where img id=$id ");
$row = mysql_fetch_array($query);
$img = $row['img'];
header("Content-type: image/jpeg");
print $img;
so this page only for displaying the pictures and when you want to use it you can do
<img src="display_img.php?id=2" />
it's not possible to keep every things in one page but also you can divide your page like this
if($$_GET['action']=="display_img"){
// show img code
}
I intend for the following code to display an 'h2' tag and text (displayed in the else statement at the bottom of the code) if there are no recorders that meet the SQL statement for a MySQL table property 'isVisible' == 1.
I decided to test to see if the query returned a 'null' result, this must be where I have a flaw in my logic. The result of my query must still be returning a value other than null even though none of the records match the "WHERE isVisible = 1" part of the SQL statement.
I only have one record in the DB hard coded to '0'. When the 'isVisible' property is returned to a value of '1' then the code executes properly. The exception is the only thing causing me trouble. I don't usually work with PHP much, so I am sure I probably just testing the wrong condition at the first if statement a few lines down.
Thanks for your time and help.
<?php
// Generate SQL Statements
$sql_position = "SELECT * FROM tbl_experience
WHERE isVisible = 1
ORDER BY 'displayPosition'";
// Run Query
$result = mysql_query($sql_position);
// Iteration Variable
$i = 0;
if ($result != null) {
// List all of the experiences as a timeline
while($row = mysql_fetch_array($result)) {
// Build a div to contain the experience properties
echo "<div id='experienceContainer_" . $row['displayPosition'] . "' class='experienceContainer";
if (i % 2) {
// The row should be displayed with 'Even' class attributes
echo " Even";
} else {
// The row should be displayed with 'Odd' class attributes
echo " Odd";
}
// Finish the opening <div> tag
echo "'>";
// Display the attributes of the experience
// Experience Type
echo "<div id='type_" . $row['displayPosition'] . "' class='experienceType'>";
switch ($row['type']) {
case 0:
echo "Undefined";
break;
case 1:
echo "Work";
break;
case 2:
echo "Achievement";
break;
case 3:
echo "Award";
break;
}
echo "</div>";
// Experience Title
echo "<div id='title_" . $row['displayPosition'] . "' class='experienceTitle'>";
echo $row['title'];
echo "</div>";
// Experience Description
echo "<div id='description_" . $row['displayPosition'] . "' class='experienceDescription'>";
echo $row['description'];
echo "</div>";
// Close the 'experienceContainer' div
echo "</div><!-- end of experienceContainer_" . $row['displayPosition'] . " -->";
}
} else {
// There are no visible records
echo "<h2>No entries for \"Experience\" can be found</h2>";
}
you need to use mysql_num_rows
if (mysql_num_rows($result) > 0) {
this if condition will guarantee that you will be routed to the else condition when there is no rows to display.
So on my blog page I am using substr to display only a bit of the articles. The idea is once someone clicks one of the headings they will be sent to a page displaying the full article.
When i click the link i get the right heading in the url for example i click the 4th blog entry i will be redirected to index.php?id=4.The problem is that on this page the content remains the same, nothing changes. How do I get it so when i click the article I will be directed to a page containing only that article in full and no others. Thanks in advance guys this has been wrecking my head all day.
<?php
$dbinfo = "SELECT blog_id, title, date, body FROM content ORDER BY blog_id DESC LIMIT 0, 3";
$result = mysql_query($dbinfo) or die(mysql_error());
$return = '<p> Go Back To Content Page</p>';
if(mysql_num_rows($result) !=0):
while($row = mysql_fetch_assoc($result)){
echo '<div id="roundedbox"><h2>' . $row['title'] . ' </h2>';
echo '<div id="date"><h5><p>' . $row['date'] . '</p></h5></div>';
echo substr('<p>' . $row['body'] . '</p>',0, 90)." .... "." read more</div>";
}
else:
echo '<p> UH OOH! THERE IS NO SUCH PAGE IT DOES\'T EXIST </p>';
echo $return;
endif;
?>
The query you have in your code will return all the records for the table, what you want is the query to return the record based on the id parameter from the $_GET['id']. It's a good idea to make sure you're only using integers to prevent sql injection.
From your code you need to have a separate query to fetch the appropriate record using the $_GET['id'] parameter as follows...
//the parameter is set and it is an integer
if(isset($_GET['id']) && is_int($_GET['id'])) {
$blogId = (int)$_GET['id'];
$query = "SELECT blog_id, title, date, body FROM content WHERE blog_id='$blogId'";
// run query and get record data and output it
} else {
//code to return all records as list
$dbinfo = "SELECT blog_id, title, date, body FROM content ORDER BY blog_id DESC LIMIT 0, 3";
$result = mysql_query($dbinfo) or die(mysql_error());
$return = '<p> Go Back To Content Page</p>';
if(mysql_num_rows($result) !=0):
while($row = mysql_fetch_assoc($result)){
echo '<div id="roundedbox"><h2><a href="index.php?id=' . $row['blog_id'].$row['title'] . ' </a></h2>';
echo '<div id="date"><h5><p>' . $row['date'] . '</p></h5></div>';
echo substr('<p>' . $row['body'] . '</p>',0, 90)." .... "." read more</div>";
}
else:
echo '<p> UH OOH! THERE IS NO SUCH PAGE IT DOES\'T EXIST </p>';
echo $return;
endif;
}
I need to write a function that does two things. It pulls a query from a mysql database and for each row found display the items of that row (There are 5 fields in the table id, title, description, timestamp, and a boolean). For each item displayed I need to have a checkbox displayed that if a user clicks the boolean is changed from off to on.
Please take this with a pinch of salt, I have not gone into any sort of security, and I'm sure there are much nicer ways but in the short time I had this might help you make a start.
<?php
$query = " SELECT id, title, description, timestamp, checkbox FROM database WHERE x = y";
$stmt = $db->prepare($query);
$stmt->execute();
echo '<form action="">';
while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
$id =$row['id'];
$title =$row['title'];
$description =$row['description'];
$timestamp =$row['timestamp'];
$checkBox =$row['checkBox'];
echo 'ID: ', $id;
echo '<br>';
echo 'Title: ', $title;
echo '<br>';
echo 'Desc: ', $description;
echo '<br>';
echo 'Time: ', $timestamp;
echo '<br>';
if (checkbox == true){
echo 'Check <input type="checkbox" name="vehicle" value="$id" checked="checked">';
}else{
echo 'Check <input type="checkbox" name="vehicle" value="$id">';
}
}
echo '</form>';
?>