How can i change this select sql statement into another select sql? - php

I have code the below code works fine but i want to have one sql statement instead of few in this code so when i try to change into one i get an error.
$eventID = $_GET['id'];
$sql = "SELECT * FROM te_events where eventID='$eventID'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$eventTitle = $row['eventTitle'];
$eventDescription = $row['eventDescription'];
$eventStartDate = $row['eventStartDate'];
$eventEndDate = $row['eventEndDate'];
$eventPrice = $row['eventPrice'];
$venueID = $row['venueID'];
$catID = $row['catID'];
$sql2 = "SELECT * FROM te_venue where venueID='$venueID'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc())
{
$venueName = $row2['venueName'];
}
$sql3 = "SELECT * FROM te_category where catID='$catID'";
$result3 = $conn->query($sql3);
while($row3 = $result3->fetch_assoc())
{
$catName = $row3['catDesc'];
}
}
?>
I changed the code into this but it seems it is not working.
<?php
$eventID = $_GET['id'];
$sql = "SELECT * FROM te_events where eventID='$eventID' AND where venueID='$venueID' From te_venue AND where catID='$catID' From te_category";
$queryresult = mysqli_query($conn, $sql) or die(mysqli_error($conn));
while ($row = mysqli_fetch_array($queryresult)) {
$eventTitle = $row['eventTitle'];
$eventDescription = $row['eventDescription'];
$eventStartDate = $row['eventStartDate'];
$eventEndDate = $row['eventEndDate'];
$eventPrice = $row['eventPrice'];
$venueID = $row['venueID'];
$catID = $row['catID'];
$catName = $row['catDesc'];
$venueName = $row['venueName'];
}
?>
And i get this error.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where venueID='' From te_venue AND where catID='' From te_category' at line 1

Yes, you can do that. But in order to get the fields that you want from all three tables, you have to join them together.
Look at this article on W3S: http://www.w3schools.com/sql/sql_join.asp. It explains SQL JOIN syntax and the basic theory behind.
If you just joined venue and event Your select statement looks like:
SELECT * FROM te_event
JOIN te_venue
ON te_vendue.venueID = te_event.venueID
WHERE te_event.eventID = $eventID
The category table is similar.
Note: In general, use of SELECT * is discouraged. Your should list the fields that you want returned from the tables. ie. SELECT te_eventID, te_venueID

You could use joins as below;
SELECT * FROM te_events
JOIN te_venue ON te_events.venueID = te_venue.venueID
JOIN te_category ON te_events.catID = te_category.catID
WHERE eventID = :EventID
As mentioned you should also use PDO's:
define( "DB_DSN", "mysql:host=localhost;dbname=foo");
define( "DB_USERNAME", "root");
define( "DB_PASSWORD", "password" );
// define sql
$sSQL = "SELECT * FROM te_events
JOIN te_venue ON te_events.venueID = te_venue.venueID
JOIN te_category ON te_events.catID = te_category.catID
WHERE eventID = :EventID";
// create an instance of the connection
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// prepare
$st = $conn->prepare( $sSQL );
// securely bind any user input in the query
$st->bindValue(":EventID", $iEventID, PDO::PARAM_INT);
// execute the connection
$st->execute()
$aResults = array();
// loop over results and store in aResults
while($row = $st->fetch()){
$aResults[] = $row;
}
// output data
foreach($aResults as $aResult){
echo "title: ".$aResult['eventTitle'];
}
You should always avoid using select *. Especially when your doing joins. Ensure you request only what you need and alias if you require duplicate column names

Related

While loop showing only one record when i use nested while loop for fetch data from another table

I have case manager table where i have inserted court table id as foreign key. i want to fetch record from both tables. when using nested while loop it shows only one row data.
$id = $_SESSION['id'];
$query1 = "SELECT * from `case_manager` where user_id = '$id' ";
$result1 = mysqli_query($conn, "$query1");
while($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$Status = $row['status'];
$id = $row['id'];
$case_type = $row['case_type'];
$court_id = $row['court_id'];
$query2 = "SELECT * from `case_type` where case_id = '$case_type'";
if($result1 = mysqli_query($conn, "$query2")) {
while($row2 = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
echo $row2['case_name'];
}
}
}
Because you are overwritting you $result1 change inner query result to $result2 then try
$id = $_SESSION['id'];
$query1 ="SELECT * from `case_manager` where user_id = '$id' ";
$result1 = mysqli_query($conn , "$query1");
while ($row = mysqli_fetch_array($result1 ,MYSQLI_ASSOC)) {
$Status=$row['status'];
$id = $row['id'];
$case_type = $row['case_type'];
$court_id = $row['court_id'];
$query2 ="SELECT * from `case_type` where case_id = '$case_type'";
if($result2 = mysqli_query($conn , "$query2")){;
while ($row2 = mysqli_fetch_array($result2 ,MYSQLI_ASSOC)) {
echo $row2['case_name'];
}
}
}
1st : Because you are overwriting the variable $result1 In second query execution.
if($result1 = mysqli_query($conn , "$query2")){;
^^^^^^^^ ^^
Note : And remove that unnecessary semicolon .
2nd : No need multiple query simple use join
SELECT cm.*,c.* from `case_manager` cm
join `case_type` c
on cm.cas_type=c.case_id
where cm.user_id=$id;
You can use below query to fetch your record:
$query = SELECT case_manager.* ,case_type.case_name FROM case_manager Left JOIN case_type ON case_manager.case_type=case_type.case_id where case_manger.user_id = $id;
While($row = mysql_fetch_array()){
echo $row['case_name'];
}

PHP select from statement

I'm trying to do a php select statement like this:
$select = mysql_query("select * from message where receiver_id = '$receiver_id'and frm_id = '$frm_id' ORDER BY id DESC");
while($row = mysql_fetch_array($select))
{
$id = urlencode(encryptor('encrypt', $result['user_id']));
$query = mysql_query($sql);
$result = mysql_fetch_assoc($query);
}
But its not working instead its select from table where frm_id = $frm_id only.
Using PDO you can do something like:
$id = "Id wanted here";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT * from `tablename` WHERE `receiver_id` = :id");
$sth->bindParam(':name', $id);
$sth->execute();
I think there are two errors.
1: you are using $result['user_id'] before defining $result.
2: $sql isn't defined.
also i am not sure about encryptor method.
You can try:
$select= mysql_query("select * from message where receiver_id = $receiver_id
and frm_id = $frm_id ORDER BY id DESC");
or
$select= mysql_query("select * from message where receiver_id = $receiver_id
or frm_id = $frm_id ORDER BY id DESC");

I have got this code it is working fine but I want to change the having code into another structure

This is the code I have at the moment which works fine:
<?php
$sql = "SELECT * FROM te_events order by eventTitle ASC ";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$venueID = $row['venueID'];
$catID = $row['catID'];
$sql2 = "SELECT * FROM te_venue where venueID='$venueID'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc())
{
$venueName = $row2['venueName'];
}
$sql3 = "SELECT * FROM te_category where catID='$catID'";
$result3 = $conn->query($sql3);
while($row3 = $result3->fetch_assoc())
{
$catName = $row3['catDesc'];
}
?>
But I want to Change it into this format. I could do only till this bit couldn't go further than this I get errors.
<?php
$sql ="SELECT eventTitle, eventID, venueID, catID, eventStartDate, eventEndDate, eventPrice FROM te_events ORDER BY eventTitle ASC";
$queryresult = mysqli_query($conn, $sql) or die(mysqli_error($conn));
while ($row = mysqli_fetch_array($queryresult)) {
$venueID = $row['venueID'];
$catID = $row['catID'];
$venueName = $row['venueName'];
$catName = $row['catDesc'];
?>
How can I do that then?
how can I join two tables?
You should be able to join the additional 2 tables to get the columns you need.
SELECT e.eventTitle, e.eventID, e.venueID, e.catID, e.eventStartDate, e.eventEndDate, e.eventPrice, v.venueName, c.catDesc
FROM te_events as e
join te_venue as v
on e.venueID = v.venueID
join te_category as c
on c.catID = e.catID
ORDER BY eventTitle ASC
You also should avoid putting data directly into a query. If you need to do that use parameterized queries. This is how SQL injections (or second level) occur.

Subquery php mysql

I have this subquery:
$sql = "SELECT * FROM curriculum WHERE ci in (SELECT curriculum FROM contactados WHERE activado = 'si' AND empresa = '".$_SESSION['emp']."' )";
echo "Rows: ".#mysql_num_rows($sql);
$result = mysql_query($sql, $link) or die(mysql_error($link));
while($fila = mysql_fetch_array($result)){
echo $fila['nombres']." ".$fila['apellidos']or die("error");
}
But it doesn´t work and I don't know why
i hope this work for you...
$sql = "SELECT `a`.*, `b`.`curriculum` FROM `curriculum` AS `a`
LEFT JOIN `contactados` AS `b` ON `a`.`ci` = `b`.`curriculum`
WHERE `b`.`activado` = 'si' AND `b`.`empresa` = '".$_SESSION['emp']."'";

MySQL run query inside a query

I have a query that gets 5 lines of data like this example below
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
}
I want to run a query inside each results like this below
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}
but for some reason it's only display the first line when I add the query inside it. I can seem to make it run all 5 queries.
SELECT
t1.ref,
t1.user,
t1.id,
t2.domain,
t2.title
FROM
table AS t1
LEFT JOIN anothertable AS t2 ON
t2.domain = t1.ref
LIMIT
0, 5
The problem is that inside the while-cycle you use the same variable $result, which then gets overridden. Use another variable name for the $result in the while cycle.
You change the value of your $query in your while loop.
Change the variable name to something different.
Ex:
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$qry = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$rslt = mysql_query($qry) or die(mysql_error());
if (mysql_num_rows($rslt) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}
Use the following :
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query_domain = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result_domain = mysql_query($query_domain) or die(mysql_error());
if (mysql_num_rows($result_domain) )
{
$row_domain = mysql_fetch_row($result_domain);
$title = $row_domain['title'];
} else {
$title = "No Title";
}
echo "$ref - $title";
}
This is a logical problem. It happens that way, because you are same variable names outside and inside the loop.
Explanation:
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
// Now $results hold the result of the first query
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
//Using same $query does not affect that much
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
//But here you are overriding the previous result set of first query with a new result set
$result = mysql_query($query) or die(mysql_error());
//^ Due to this, next time the loop continues, the $result on whose basis it would loop will already be modified
//..............
Solution 1:
Avoid using same variable names for inner result set
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$sub_result = mysql_query($query) or die(mysql_error());
// ^ Change this variable so that it does not overrides previous result set
Solution 2:
Avoid the double query situation. Use joins to get the data in one query call. (Note: You should always try to optimize your query so that you will minimize the number of your queries on the server.)
SELECT
ref,user,id
FROM
table t
INNER JOIN
anothertable t2 on t.ref t2.domain
LIMIT 0, 5
Learn about SQL joins:
SELECT table.ref, table.user, table.id, anothertable.title
FROM table LEFT JOIN anothertable ON anothertable.domain = table.ref
LIMIT 5
You're changing the value of $result in your loop. Change your second query to use a different variable.
it is not give proper result because you have used same name twice, use different name like this edit.
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query1 = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result1 = mysql_query($query1) or die(mysql_error());
if (mysql_num_rows($result1) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}

Categories