Any ideas why this simple php code won't display results when trying to echo the data.
<?php
{
mysql_connect("localhost" , "" , "") or die (mysql_error());
mysql_select_db("") or die(mysql_error());
$pid=intval($_SESSION["User_id"]);
$query = "SELECT `car`, `details`, `price` FROM `Car``";
//executes query on the database
$result = mysql_query ($query) or die ("didn't query");
//this selects the results as rows
$num = mysql_num_rows ($result);
while($row=mysql_fetch_assoc($result))
{
$_SESSION['car'] = $row['car'];
$_SESSION['details'] = $row['details'];
$_SESSION['price'] = $row['price'];
}
}
?>
<?php echo $_SESSION['car']; ?>
<?php echo $_SESSION['details']; ?>
<?php echo $_SESSION['price']; ?>
Just testing at the moment to see if the car, price and details display from the database and they don't seem to.
You missed session_start(); at start of page and change
$query = "SELECT `car`, `details`, `price` FROM `Car``";
^
to
$query = "SELECT `car`, `details`, `price` FROM `Car`";
Are you expecting one or many results for this query ?
If many results, you are saving the last entry in the session.
If only one, just do : $row=mysql_fetch_assoc($result) instead of this while.
Check the query.Try to echo it, copy, paste in MySQL and run it. But you have $pid, have you put it in the query?
$query = "SELECT car, details, price FROM Car WHERE id = $pid ";
I rather remove all backticks since non of those identifiers are reserved keywords.
$query = "SELECT car, details, price FROM Car";
Related
I have a column in a table that I would like to add up and display the result in a textbox. But its not working.
<?php
function getpoint(){
$query = "SELECT sum(monthly_point) FROM characters WHERE
inmate_id = '$value'";
$result_set = mysql_query($query);
$row = mysql_fetch_array($result_set);
echo 'sum:'. $row[0];
}
?>
Switch to mysqli instead of mysql functions (out of date and not as secure) and parameterized statements. Your code is susceptible to SQL injection.
Two problems in your code. Add an alias to the sum column, and reference the column in the echo statement:
<?php
function getpoint() {
$query = "SELECT sum(`monthly_point`) as `sum` FROM characters WHERE inmate_id = '$value'";
$result_set = mysql_query($query);
$row = mysql_fetch_array($result_set);
echo 'sum:'. $row[0]['sum'];
}
?>
When you use var_dump() to display $row then it's OK ?
Please look it and add parameter as below
echo 'sum:'. $row['xxxxx'];
'xxxxx' : parameter
I am trying to count the total number of rows in a single table. Just need to know how many rows total and nothing else. I am using Oracle database.
I have tried
$sql = "SELECT COUNT(*) AS homes FROM homes";
But I am unsure on how to display the result.
$sql = "SELECT COUNT(*) AS count FROM homes";
To count the rows from
$sql = "SELECT * FROM homes"; // fetch the rows
$sql1=mysql_query($sql);
$count=mysql_num_rows($sql1) // count number of rows in table
echo $count; //$count has the value of rows in table..
Use this code:
// Code goes here
<?php
$sql = "SELECT COUNT(*) AS homes FROM homes";
$result = mysqli_query($sql);
$row = mysqli_fetch_array($result);
print($row['homes']); // prints count
?>
<?php
$link = mysqli_connect("host", "username", "password");
mysqli_select_db("database", $link);
$result = mysqli_query("SELECT * FROM homes", $link);
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n";
?>
I am trying to insert to another table the results of a select statement from another table. The select statement works but the insert statement does not work. Please help me.
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
}
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
header("Location:homeclient.php");
?>
You asked for how to do these two as one query.
This is how:
$query = mysql_query("INSERT INTO `client` ( `client_csub_code`, `client_csub_name`, `client_csub_day`, `client_csub_time` ) SELECT `sub_code`, `sub_name`, `sub_day`, `sub_time` FROM `subject` WHERE `code` = '$enrol'");
// I would also add error checking
if ( mysql_errno() )
echo mysql_error();
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
}
header("Location:homeclient.php");
?>
Try changing to this. Currently your query is outside of your while, it will only run once and the values of $csubject etc are always going to be the last values of your fetched results.
I want to show the maximum value of a particular column of mysql table in php. Here is my code:
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$var = $_POST['value'];
$sql = mysql_query(" SELECT MAX(column) FROM tableName WHERE variable='$var' ") or die(mysql_error());
$row = mysql_fetch_array($sql) or die(mysql_error());
echo "Maximum value is :: ".$row['column'];
?>
output:::
Maximum value is ::
Or you could be a bit creative:
$sql = mysql_query("SELECT `column` FROM tableName WHERE variable='$var' ORDER BY `column` DESC LIMIT 1") or die(mysql_error());
This is the same problem that I was searching for a solution. The approach below worked. The solution was using "MYSQLI_NUM". While the code below gives the intended result it still seems way too complex. Is there a way to "short-cut" using the "while" statement to search an array since there is only one returned value?
Selecting a max value only returns one number, yet PHP still seems to require a loop to evaluate an entire array. I was expecting something easy, like: max_value=result(0).
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error.' Sorry, could not connect to the database server');
$query = "SELECT MAX(IssueIDNUM) FROM tblIssueList";
$result =$conn->query($query);
if (!$result) die($conn->error);
while($row=mysqli_fetch_array($result, MYSQLI_NUM))
{
$maxresult=$row[0];
echo $maxresult;
}
$result->close();
$conn->close();
?>
With further experimentation, I was also able to adapt the code by Jim H. to develop the following solution. Though it works the code still seems too complex.
// Solution #2
$result =$conn->query("SELECT MAX(IssueIDNUM) `max` FROM tblIssueList");
if (!$result) die($conn->error);
while($row=mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo $row['max'];
}
The real name of column is MAX(column), try:
print_r($row);
You may either do:
$sql = mysql_query(" SELECT MAX(column) AS `column` FROM tableName WHERE variable='$var' ") or die(mysql_error());
Or:
$row = mysql_fetch_row($sql) or die(mysql_error());
echo "Maximum value is :: ".$row[0];
You have two choices. By Index or by Column Name. If you really want to use a column name, alias the column in your query.
$sql = mysql_query(" SELECT MAX(column) `max` FROM tableName WHERE variable='$var' ") or die(mysql_error());
Then you can use
$row['max'];
or
$row[0];
You are probably not returning any rows. You should try WHERE variable LIKE '%$var%';
$sql = mysql_query(" SELECT MAX(column) AS GIVE_A_NAME FROM tableName WHERE variable='$var' ") or die(mysql_error());
and
echo "Maximum value is :: ".$row['GIVE_A_NAME'];
I have 2 tables in my database. categories and products. in categories there are 2 fields. catid and catname. and in products also there are 3 fields. id, catid and name.
in my submit form im fetching the catname in to a sector. what i wanna do is get value of the selector and save the catid in to products table catid field. instead of categories name. can anyone explain me how to do this. Thanks in advance.
Here is the code of submit form.
include("db.php");
$result = mysql_query("SELECT * FROM categories")
or die (mysql_error());
?>
<!--SubmitForm-->
<form method="post" action="add_products.php">
<select name="cat">
<?php
while($row = mysql_fetch_array($result))
{echo "<option value='".$row[catid]."'>".$row[catname]."</option>";}
?>
</select><br/>
<input type="text" name="name" value=""><br/>
<input type="submit" value="submit"/>
</form>
add_products.php Code
<?php
include("db.php");
$cat = $_POST['catid'];
$query = "SELECT * FROM categories WHERE catname='$cat'";
$result= mysql_query($query) or die ('Mysql Error');
while($row = mysql_fetch_array($result)){
$catn = $row['catid'];
}
$name = mysql_real_escape_string($_POST['name']);
$query="INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
?>
You already seem to have the right values, just need to put them in the correct spot, if you need the 'catid', you can just put it in the id tag of the select.
When you echo the you just need to do this,
echo "<option id='".$row[catid]."' value='".$row[cat]."'>".$row[catname]."</option>";
For more info refer to the w3school manual for , at this link.
Some unrelated, but very important things:
you should escape $cat before it goes into the query
you should always escape strings that go out to HTML with htmlspecialchars
you should always use $row['keyname'], not the deprecated $row[keyname]
Now for your question. The code seems correct on first glance, but I don't have PHP right now so I can't test it. Is there anything in particular that is not working as expected?
You already have it in??
$cat = $_POST['catid'];
If you only want to insert IF they $cat exists, then:
<?php
include("db.php");
$cat = $_POST['catid'];
$query = "SELECT * FROM categories WHERE catname='$cat'";
$result= mysql_query($query) or die ('Mysql Error');
if($result)
{
$name = mysql_real_escape_string($_POST['store']);
$query="INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
}
?>
You are already assigning the category ID to the category name in the select menu. The variable of the select menu is $_REQUEST['cat'], which holds the ID of the selected category after submitting the form. You can save this value directly to the product table.
However, the while loop in add_products.php is of no use, since you are always assigning the last ID in the table to the variable $catn. Replace this while loop with $catn = $_REQUEST['cat'] (while cat is the name of the select menu).
seem many mistakes here:
select name="cat"
and your try to receive $cat = $_POST['catid']; the correct is $cat = $_POST['cat'];
then you tries to select by catname
$query = "SELECT * FROM categories WHERE catname='$cat'";
when you need to compare ids catid='$cat'";
and what for to assign meny times if the result is single?:
if ( ($row = mysql_fetch_array($result)) ){
$catn = $row['catid'];
}
Your select field is names 'cat', so it should be $_POST['cat'] (or better, rename the select field to 'catid'). And it alreay contains the catid, so there's no need to get it from the DB again (unless you want to make sure it does in fact exist).
Finally, you should escape the $_POST['cat'] parameter as you do the name.
So this is sufficient:
$catid = mysql_real_escape_string($_POST['cat']);
$name = mysql_real_escape_string($_POST['store']);
$query="INSERT INTO products(catid, name) VALUES ('".$catid"','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
Please also look into PDO for the best way to handle DB queries like this.
try change this
"INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
to
"INSERT INTO products(catid, name)VALUES ('".$cat."','".$name."')";