could not get data from sqli in php - php

I am trying display those values from database but it shows an error which is written in if condition plz tell me where i am doing wrong????
$sql1 = "SELECT * FROM Batch b, Vendor v, Product p WHERE 'v.id' = 'b.id', 'p.id' = 'b.id' and 'b.batch_no' = $batchno";
$retval = mysqli_query($conn,$sql1);
if(!$retval)
{
die('Could not get data:' . $conn->connect_error);
}
else
{
echo "<input type = 'submit' value = 'Print Bill'><br>";
echo "<h3>Bill</h3>";
while($row = mysqli_fetch_array($retval,MYSQL_ASSOC))
{
echo "Vendor Name :{$row['name']} <br> " .
"Batch No:{$row['batchno']} <br> " .
"Product Size:{$row['product_size']} <br> " .
"Product Price Per Unit:{$row['product_price']} <br> " .
"Product Quantity:{$row['quantity']} <br> " .
"------------------------------<br>";
}
}

first check your connection if your connected on your database
and try
"SELECT * FROM batch b Inner join Vendor v on v.id=b.id inner join Product p on p.id=b.id where b.batch_no=".$batchno

You have to join the tables and then use 'on' to tell it how to link the tables.
http://dev.mysql.com/doc/refman/5.0/en/join.html
Also not sure what $batchno but that maybe opening your query to injections. http://en.wikipedia.org/wiki/SQL_injection

There is and instead of , in your sql query
$sql1 = "SELECT * FROM Batch b, Vendor v, Product p WHERE 'v.id' = 'b.id' and 'p.id' = 'b.id' and 'b.batch_no' = $batchno";

Related

Need to add a Group By statement to PHP/SQL generated from Codecharge

I am trying to modify some PHP code that was created ages ago in Codecharge, to include a Group By clause in a MYSQL statement.
I have tested my MYSQL query and it works brilliantly in phpmyadmin. When I bring it in to the php page it kicks back an error because the WHERE and ORDER clauses are coded in separate locations, and then called in to the query string. Obviously, when the GROUP BY is left in the SQL it breaks because it is inserting it before the WHERE in the $this chain, so I need to figure out where I can insert the GROUP BY part of the code so it strings it all together in the proper order and the page loads as it should. Below is the 3 sections that pull together the SQL and clauses, and the webpage loads fine. I commented out by version of the SQL as it doesnt work properly without the GROUP BY.
//SetOrder Method #5-0FECF370
function SetOrder($SorterName, $SorterDirection)
{
$this->Order = "book_name";
$this->Order = CCGetOrder($this->Order, $SorterName, $SorterDirection,
"");
}
//End SetOrder Method
//Prepare Method #5-C6449552
function Prepare()
{
$this->wp = new clsSQLParameters($this->ErrorBlock);
$this->wp->AddParameter("1", "urlshow_id", ccsInteger, "", "", $this->Parameters["urlshow_id"], "", false);
$this->wp->Criterion[1] = $this->wp->Operation(opEqual, "ttb_books.show_id", $this->wp->GetDBValue("1"), $this->ToSQL($this->wp->GetDBValue("1"), ccsInteger),false);
$this->Where = $this->wp->Criterion[1];
}
//End Prepare Method
//Open Method #5-33D1EC54
function Open()
{
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeBuildSelect");
$this->CountSQL = "SELECT COUNT(*) " .
"FROM (ttb_books INNER JOIN ttb_states ON " .
"ttb_books.state_id = ttb_states.state_id) INNER JOIN ttb_statuses ON " .
"ttb_books.status_id = ttb_statuses.status_id";
$this->SQL = "SELECT * " .
"FROM (ttb_books INNER JOIN ttb_states ON " .
"ttb_books.state_id = ttb_states.state_id) INNER JOIN ttb_statuses ON " .
"ttb_books.status_id = ttb_statuses.status_id ";
//$this->SQL = "SELECT ttb_books.book_id, ttb_books.book_name, ttb_books.show_id, ttb_states.state_name, COUNT(ttb_imgs.img_id) AS images " .
//"FROM (ttb_books INNER JOIN ttb_states ON ttb_books.state_id = ttb_states.state_id) " .
//"INNER JOIN ttb_statuses ON ttb_books.status_id = ttb_statuses.status_id " .
//"LEFT JOIN ttb_imgs ON ttb_books.book_id = ttb_imgs.book_id ";
$this->Group = "ttb_books.book_id, ttb_books.book_name, ttb_books.show_id, ttb_states.state_name";
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeExecuteSelect");
$this->RecordsCount = CCGetDBValue(CCBuildSQL($this->CountSQL, $this->Where, ""), $this);
$this->query(CCBuildSQL($this->SQL, $this->Where, $this->Order));
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterExecuteSelect");
$this->MoveToPage($this->AbsolutePage);
}
//End Open Method
The original version of the code just lists all the book titles, and sorts by book name. My version also includes a COUNT, because I want to not only see all the book titles, but also a page count for each book in the list. Like I said, my new SQL works fine in phpmyadmin, and I'm sure it would on the page too if I could get the Grouping to work properly, too. Thank you for your help!
Ok, here is what I did. I stripped out the $this->Where part of the CCBuildSQL line, and put the WHERE directly in to the sql statement, which allowed me to use my GROUP BY and get the results I was looking for.
function Open()
{
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeBuildSelect");
$this->CountSQL = "SELECT COUNT(*) " .
"FROM (ttb_books INNER JOIN ttb_states ON " .
"ttb_books.state_id = ttb_states.state_id) INNER JOIN ttb_statuses ON " .
"ttb_books.status_id = ttb_statuses.status_id";
$this->SQL = "SELECT ttb_books.book_id, ttb_books.book_name, ttb_books.owned, ttb_books.show_id, ttb_shows.show_name, ttb_states.state_name, COUNT(img_id) AS images " .
"FROM ttb_books " .
"INNER JOIN ttb_states ON ttb_books.state_id = ttb_states.state_id " .
"INNER JOIN ttb_statuses ON ttb_books.status_id = ttb_statuses.status_id " .
"INNER JOIN ttb_shows ON ttb_books.show_id = ttb_shows.show_id " .
"LEFT JOIN ttb_imgs ON ttb_books.book_id = ttb_imgs.book_id WHERE ttb_books.show_id=" . $this->Parameters["urlshow_id"] .
" GROUP BY ttb_books.book_id, ttb_books.book_name, ttb_books.owned, ttb_books.show_id, ttb_shows.show_name, ttb_states.state_name " ;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeExecuteSelect");
$this->RecordsCount = CCGetDBValue(CCBuildSQL($this->CountSQL, $this->Where, ""), $this);
$this->query(CCBuildSQL($this->SQL, "", $this->Order));
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterExecuteSelect");
$this->MoveToPage($this->AbsolutePage);
}
It looks like you're not in the IDE and directly altering the generated code. Go into the CodeCharge IDE, choose the control you want to modify, then create a Custom Code Event and put your adjusted SQL there.
http://docs.codecharge.com/studio50/html/index.html?http://docs.codecharge.com/studio50/html/ProgrammingTechniques/HowTo/CustomizingDataSource/ModifyOrderBy.html?toc

PHP - SQL Query filter+

I am working on a php script that will get the required information and display it in an xml. For some reason my brin isn't work and I don't know how to do the query. The database has two tables that I want to pull information from. Both tables have one thing in common which is 'id_member'. Themes table has a bunch of junk in it - so it has 4 coulms - 'id_member', 'id_theme', 'varible', and 'value'. There are two items in 'varible' that I want to filter (show them and not the rest) "cust_armaus" and "cust_armamo" then value will show the value of course. So in the table Themes it will have id_member listed more than once to show the different varibles. This is what I got that isn't working for me:
<?php
header('Content-Type: text/xml');
$username="database_username";
$password="database_password";
$database="database_name";
mysql_connect('localhost',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
echo "<?xml version=\"1.0\"?>\n".
"<!DOCTYPE squad SYSTEM \"squad.dtd\">\n".
"<?xml-stylesheet href=\"squad.xsl?\" type=\"text/xsl\"?>\n";
?>
<squad nick="Team Tag">
<name>Team Name</name>
<email>contact#team.com</email>
<web>http://www.team.com</web>
<picture>teamlogo.paa</picture>
<title>This is the Team motto</title>
<?php
// smf_themes -> id_member =
// smf_themes -> variable for cust_armaus & cust_usermo
// smf_themes -> value <- get for cust_armaus & cust_usermo
// smf_members -> real_name = profile_name & name
// smf_members -> email_address = email - NO
$memberSQL = mysql_query("SELECT id_member AS id, real_name FROM smf_members");
$member = mysql_fetch_array($memberSQL);
$armausSQL = mysql_query("SELECT id_member, variable, value AS arma_id FROM smf_themes WHERE id_member='$member[id]' AND variable='cust_armaus'");
$armaid = mysql_fetch_array($armausSQL);
$armamoSQL = mysql_query("SELECT id_member, variable, value AS motto FROM smf_themes WHERE id_member='$member[id]' AND variable='cust_usermo'");
$armamo = mysql_fetch_array($armamoSQL);
$num=mysql_numrows($member, $armaid, $armamo);
mysql_close();
$i=0;
while ($i < $num) {
$profile_id = mysql_result($armaid,$i,"value");
$profile_name = mysql_result($member,$i,"real_name");
$profile_remark = mysql_result($armamo,$i,"value");
$profile_username = mysql_result($member,$i,"real_name");
//$profile_email = mysql_result($result,$i,"email");
//$profile_icq = mysql_result($result,$i,"icq");
echo "<member id=\"$profile_id\" nick=\"$profile_name\">" .
"<name>$profile_name</name>".
"<email>$profile_email</email>".
"<icq>$profile_icq</icq>".
"<remark>$profile_remark</remark>".
"</member>\n";
$i++;
}
?>
</squad>
The mysql interface is deprecated. New development should use either mysqli or PDO.
Assuming you only one one value of the cust_armaus and cust_usermo rows for each smf_members, you could use correlated subqueries in the SELECT list, and return just a single query that returns a single row for each row in smf_members. Something like this:
SELECT m.id_member AS id
, m.real_name
, (SELECT a.value
FROM smf_themes a
WHERE a.id_member = m.id_member
AND a.variable = 'cust_armaus'
ORDER BY a.value LIMIT 1
) AS cust_armaus
, (SELECT u.value
FROM smf_themes u
WHERE u.id_member = m.id_member
AND u.variable = 'cust_usermo'
ORDER BY u.value LIMIT 1
) AS cust_usermo
FROM smf_members m
ORDER BY m.id_member
If the (id_member,variable) tuple is guaranteed to be unique in smf_themes, you could use a simpler outer join:
SELECT m.id_member AS id
, m.real_name
, a.value AS cust_armaus
, u.value AS cust_usermo
FROM smf_members m
LEFT
JOIN smf_themes a
ON a.member_id = m.member_id AND a.variable = 'cust_aramus'
LEFT
JOIN smf_themes u
ON u.member_id = m.member_id AND u.variable = 'cust_usermo'
ORDER BY m.id_member
With either of those queries, you could use code something like this:
$sql = "SELECT ...";
$rs = $mysqli->query($sql)
if (!$rs) {
// handle error
echo 'query failed: (' . $mysqli->errno . ') ' . $mysqli->error;
die;
}
// loop through rows returned
while ( $row = $rs->fetch_assoc() ) {
echo '<member id="' . htmlspecialchars($row['id']) . '"'
. ' nick="' . htmlspecialchars($row['real_name']) . '">'
. '<cust_aramus>' . htmlspecialchars($row['cust_aramus']) . '</cust_aramus>'
. '<cust_usermo>' . htmlspecialchars($row['cust_usermo']) . '</cust_usermo>' ;
}

PHP displaying data from four tables in one query (ie: LEFT JOIN)

I have three tables:
I want to display 'Event Details' which shows attending employee details (listo f employee ids from the 'attending_employees table > corresponding employee details form 'employee' table), what team they belong to (from the club_teams table) and the event details from the 'club_events' table).
Currently I am using multiple mysqli queries to display this information however cannot get my head around pulling the data from the database in one query (ie: LEFT JOIN). Your assistance would be greatly appreciated!
Below are the queries i am currently using:
$query = msqli_query($con, "SELECT * FROM attending_employees")or die(mysqli_error($con));
if(mysqli_num_rows($query) > 0){
while($attending = mysqli_fetch_array($query)){
foreach($attending['club_event']){
$eventid = $attending['club_event'];
$query = msqli_query($con, "SELECT * FROM club_events WHERE club_event_id = '$eventid'")or die(mysqli_error($con));
while($event_details = mysqli_fetch_array($query)){
// Echo event details
}
}foreach($attending['employee']){
$empid = $attending['employee'];
$query = msqli_query($con, "SELECT * FROM employees WHERE employee_id = '$empid'")or die(mysqli_error($con));
while($event_employees = mysqli_fetch_array($query)){
// Echo employee details
}
}foreach($attending['team']){
$teamid = $attending['team'];
$query = msqli_query($con, "SELECT * FROM club_teams WHERE clb_team_id = '$teamid'")or die(mysqli_error($con));
while($event_team = mysqli_fetch_array($query)){
// Echo team details
}
}
}
}
This method is highly inefficient and wasteful since its retrieving duplicate data (ie: all repeated 'club_event_id's in the 'attending_employees' table.)
Try this:
$query = msqli_query(
$con,
"SELECT"
. " attending_employees.*"
. ", club_events.*"
. ", employees.*"
. ", club_teams.*"
. " FROM"
. " attending_employees"
. " LEFT JOIN club_events ON club_events.club_event_id = attending_employees.club_event"
. " LEFT JOIN employees ON employees.employee_id = attending_employees.employee"
. " LEFT JOIN club_teams ON club_teams.clb_team_id = attending_employees.team"
) or die(mysqli_error($con));

if statement to check if mysql row exists, then selecting next query

I'm attempting to select a query to use based on the number of rows returned by a test result.
$id = mysql_real_escape_string(htmlspecialchars($_POST['id']));
$result = "SELECT FROM Notifications WHERE UserID=$id";
$r = e_mysql_query($result);
$row = mysql_fetch_array($r);
$num_results = mysql_num_rows($result);
$result = '';
if ($num_results != 0) {
$result =
"SELECT U.UserID,U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U, Notifications N " .
" WHERE U.LocationID=0 " .
" AND N.UserID='$id'";
} else {
$result =
"SELECT UserID, FirstName, LastName," .
" DATE_FORMAT(BirthDate, '%m-%d-%Y') AS BirthDate " .
" FROM Users " .
" WHERE LocationID = 0 " .
" AND UserID ='$id'";
}
echo $result;
e_mysql_result($result); //Bastardized/homegrown PDO
if ($row = mysql_fetch_assoc($result)) {
$retValue['userInfo'] = $row;
...
I'm checking the Notifications table to see if the UserID exists there, if it doesn't it loads what does exist from the Users table, if it does, then it loads everything from the Notifications table.
I'm echoing out the $result and the proper statement is loaded, but it doesn't execute. When I run the concatenated query I get from the PHP preview, it returns just fine.
Before I had to if/else this, I was running the first query, loading everything from the Notifications table, and it was loading just fine. What am I missing?
You can do the whole thing with one query with a LEFT JOIN.
$query= "SELECT U.UserID, U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U " .
" LEFT JOIN Notifications N " .
" ON U.UserID = N.UserID " .
" WHERE U.UserID = '$id'";
You are missing execute a query with mysql_query() on all $result
Also change (query variable should be quoted) so change your all variables $id quoted
$result = "SELECT FROM Notifications WHERE UserID=$id";
to
$result = "SELECT FROM Notifications WHERE UserID='$id'";
$r = mysql_query($result);
Note :- mysql_* has been deprecated use mysqli_* or PDO

PHP MySQL - Inner Join only if not null

I have a mysqli SELECT query that is using an Inner Join and I noticed a big problem: it doesn't select rows where the column value for the condition is null (because NULL doesn't exist in the second table). Here's my code:
<?php
$sql = mysqli_connect(/* CONNECTION */);
$query = "SELECT " .
"e.EQUIPMENT_ID, " .
"e.CUSTOMER_ID, " .
"e.DESCRIPTION, " .
"e.LOCATION, " .
"e.JOB_SITE, " .
"e.PROJECT_NAME, " .
"jb.DESCRIPTION AS JOB_SITE_NAME " .
"FROM equipments e " .
"INNER JOIN jobsites jb ON jb.JOBSITE_ID = e.JOB_SITE " .
"WHERE e.CUSTOMER_ID = 1 ".
"ORDER BY e.EQUIPMENT_ID ASC";
$results = mysqli_query($sql, $query);
if(!isset($data)) $data = array(); $cc = 0;
while($info = mysqli_fetch_array($results, MYSQLI_ASSOC)){
if(!isset($data[$cc])) $data[$cc] = array();
///// FROM TABLE equipments /////
$data[$cc]['EQUIPMENT_ID'] = $info['EQUIPMENT_ID'];
$data[$cc]['DESCRIPTION'] = $info['DESCRIPTION'];
$data[$cc]['LOCATION'] = $info['LOCATION'];
$data[$cc]['PROJECT_NAME'] = $info['PROJECT_NAME'];
$data[$cc]['JOB_SITE_ID'] = $info['JOB_SITE'];
///// FROM TABLE jobsites /////
$data[$cc]['JOB_SITE'] = $info['JOB_SITE_NAME'];
$cc++;
}
print_r($data);
?>
So, as I said, the code returns values but only if the column "JOB_SITE" inside "equipments" has a jobsite id (not null). The ugly solution is to create a row inside the table "jobsites" with a jobsite_id named "empty", but if I can skip this, I will.
Is there a way to join only if e.JOB_SITE is not null ?
You can use LEFT JOIN in SQL query.
$query = "SELECT " .
"e.EQUIPMENT_ID, " .
"e.CUSTOMER_ID, " .
"e.DESCRIPTION, " .
"e.LOCATION, " .
"e.JOB_SITE, " .
"e.PROJECT_NAME, " .
"jb.DESCRIPTION AS JOB_SITE_NAME " .
"FROM equipments e " .
"LEFT JOIN jobsites jb ON jb.JOBSITE_ID = e.JOB_SITE " .
"WHERE e.CUSTOMER_ID = 1 ".
"ORDER BY e.EQUIPMENT_ID ASC";
This query will return NULL VALUE for column JOB_SITE_NAME if there is no row matching jb.JOBSITE_ID in equipments table

Categories