I'm trying almost everything to add a new key and its value to a result query.
$consulta = "SELECT p.id_empleado,count(p.id_empleado) as pendientes,e.nombre,e.apellidos FROM partidas_empleados p ";
$consulta.= "inner join empleados e on p.id_empleado=e.id_empleado ";
$consulta.= "WHERE abierta=TRUE group by id_empleado";
$sql = $con->prepare($consulta);
$ok = $sql->execute();
$query = $sql->fetchAll(PDO::FETCH_ASSOC);
for($i=0;$i<count($query);$i++){
//echo "hola";
$fila = $query[$i];
$consulta = "SELECT id_partida FROM partidas_empleados where id_empleado=? ";
$sql = $con->prepare($consulta);
$ok = $sql->execute(array($fila['id_empleado']));
$sub_query = $sql->fetchAll(PDO::FETCH_ASSOC);
//echo $sub_query;
//$fila[]= array("lista_partidas"=>$sub_query);
$fila['lista_partidas']= $sub_query;
}
$sub_query is just a list of asociative arrays
I'm trying to add $sub_query to $query with lista_partidas as a key.
As #kunruh and #jeroen said I was creating a copy of and modifying that copy.
$consulta = "SELECT p.id_empleado,count(p.id_empleado) as pendientes,e.nombre,e.apellidos FROM partidas_empleados p ";
$consulta.= "inner join empleados e on p.id_empleado=e.id_empleado ";
$consulta.= "WHERE abierta=TRUE group by id_empleado";
$sql = $con->prepare($consulta);
$ok = $sql->execute();
$query = $sql->fetchAll(PDO::FETCH_ASSOC);
for($i=0;$i<count($query);$i++){
$consulta = "SELECT id_partida FROM partidas_empleados where id_empleado=? ";
$sql = $con->prepare($consulta);
$ok = $sql->execute(array($fila['id_empleado']));
$sub_query = $sql->fetchAll(PDO::FETCH_ASSOC);
$query[$i]['lista_partidas']= $sub_query;
}
Related
How would I get this to work, because I am just getting errors right now.
$_GET['providers'] is an array of DB column names, which I am checking if = 1 in the below query.
foreach ($_GET['providers'] as $providers) {
$statement = "AND ".$providers."= '1' ";
}
$sql = "select * from users where user_id ='1' ".$statement." ";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
echo "It worked";
}
You should use a whitelist to check if the $providers are known column names. You then should concatenate the $statement, otherwise you overwrite that variable on every iteration.
$statement = '';
$columns = array('known', 'columns', 'go', 'here');
foreach ($_GET['providers'] as $providers) {
if(in_array($providers, $columns)) {
$statement .= " AND $providers = 1 ";
}
}
$sql = "select user_id from users where user_id =1 $statement limit 1";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
echo "It worked";
}
You also shouldn't use * unless you really want every column. If you just want to see if a row is returned you also can use limit 1 because you don't care about other rows.
You are overwriting $statement every time the loop is running.
$statement = "";
foreach ($_GET['providers'] as $providers) {
$statement .= "AND ".$providers."= '1' "; // note the ".=" to append
}
$sql = "select * from users where user_id ='1' ".$statement." ";
// to debug: echo "Query :: $sql";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
echo "It worked";
}
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
I am trying to get the key value from the multidimensinal array which I have created using .The Array snapshot is given after the Code.
Below is my PHP code-
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link,$selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if($numOfTicket > 0){
$allRowData = array();
while($row = mysqli_fetch_assoc($rsTicket)){
$allRowData[] = $row;
}
$key = 'array(1)[ticketID]';
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', array_keys($key)).")";
Array Snapshot-
I need the tickedID value from this array . Like the first one is 49 .
Please help.
change your code like
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link, $selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if ($numOfTicket > 0) {
$allRowData = array();
while ($row = mysqli_fetch_assoc($rsTicket)) {
$allRowData[] = $row['ticketID'];
}
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (" . implode(',', $allRowData) . ")";
$ids = array_column( $allRowData, 'ticketID'); //this will take all ids as new array
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', $ids).")";
You should do a single query using JOIN for this:
$query = "
SELECT t.*
FROM ticket t
JOIN ticketusermapping tum
ON t.ticketID = tum.ticketID
AND tum.userID = '$userID'
AND tum.distanceofticket <= '$miles'
";
$stmt = mysqli_query($link, $query);
$numOfTickets = mysqli_num_rows($stmt);
while($row = mysqli_fetch_assoc($stmt)){
var_dump($row); // here will be the ticket data
}
Following is my code,
$result1 = "SELECT emp_id FROM employee where manager_id=".$userID;
$array = mysql_query($result1);
$cnt = 0;
while ($row = mysql_fetch_array($array)) {
"emp_id: " . $row[0];
$myArrayOfemp_id[$cnt] = $row[0];
$cnt++;
}
var_dump($myArrayOfemp_id);
$sql = "SELECT emp_id FROM emp_leaves WHERE emp_id='$myArrayOfemp_id' ORDER BY apply_date DESC";
$result = mysql_query($sql);
$total_results = mysql_num_rows($result);
When I'am trying to use $myArrayOfemp_id variable in $sql query, It shows that error:
Array to string conversion in..
How can I fix it?
You are trying to convert an array into a string in the following line:
$sql = "SELECT emp_id FROM emp_leaves
WHERE emp_id='$myArrayOfemp_id' ORDER BY apply_date DESC";
$myArrayOfemp_id is an array. That previous line of code should be changed to:
$sql = "SELECT emp_id FROM emp_leaves
WHERE emp_id={$myArrayOfemp_id[0]} ORDER BY apply_date DESC";
I placed 0 inside {$myArrayOfemp_id[0]} because I'm not sure what value want to use that is inside the array.
Edited:
After discussing what the user wanted in the question, it seems the user wanted to use all the values inside the array in the sql statement, so here is a solution for that specific case:
$sql = "SELECT emp_id FROM emp_leaves
WHERE ";
foreach ($myArrayOfemp_id as $value)
{
$sql .= " emp_id={$value) || ";
}
$sql .= "1=2";
$result = mysql_query($sql);
$total_results = mysql_num_rows($result);
$sql = "SELECT emp_id FROM emp_leaves WHERE emp_id in
(SELECT GROUP_CONCAT(emp_id) FROM employee where manager_id=".$userID.")
ORDER BY apply_date DESC";
$result = mysql_query($sql);
$total_results = mysql_num_rows($result);
just change your query like above might solve your problem.
you can remove following code now. :)
$result1 = "SELECT emp_id FROM employee where manager_id=".$userID;
$array = mysql_query($result1);
$cnt = 0;
while ($row = mysql_fetch_array($array)) {
"emp_id: " . $row[0];
$myArrayOfemp_id[$cnt] = $row[0];
$cnt++;
}
var_dump($myArrayOfemp_id);
if user select anything besides "all" it will lead to a where statement involving KodDaerah
$where = '';
$sql= "SELECT * FROM maklumatakaun
LEFT JOIN detailakaun ON maklumatakaun.id = detailakaun.id
LEFT JOIN maklumatbilakaun ON maklumatakaun.NoAkaun = maklumatbilakaun.NoAkaun
LEFT JOIN kodjenisakaun ON detailakaun.KodJenisAkaun = kodjenisakaun.KodJenisAkaun
LEFT JOIN kodlokasi ON detailakaun.KodLokasi = kodlokasi.KodLokasi
LEFT JOIN kodkategori ON maklumatakaun.KodKategori = kodkategori.KodKategori
LEFT JOIN koddaerah ON maklumatakaun.KodDaerah = koddaerah.KodDaerah
WHERE maklumatakaun.KodKategori = '$KodKategori'
AND detailakaun.KodJenisAkaun = '$KodJenisAkaun'
AND maklumatbilakaun.BulanBil = '$BulanBil'
AND maklumatbilakaun.TahunBil ='$TahunBil'
".mysql_real_escape_string($where)."
ORDER BY koddaerah.NamaDaerah ";
if($KodDaerah != "all"){
$where = "AND maklumatakaun.KodDaerah = '$KodDaerah' "; //Add your where statement here
//Whatever you want to do
}
else {
$where = "";
}
if user select all then the system will just use the current sql statement that i provided, for now im not sure what's wrong, so here is where user select the KodDaerah from drop down list box
<?php include('dbase.php');
$sql = "SELECT KodDaerah, NamaDaerah FROM koddaerah";
$result = mysql_query($sql);
echo "<select name='KodDaerah' id='KodDaerah' class='input_field' required />
<option>Pilih Daerah</option>
<option value='all'>Seluruh Pahang</option>";
while ($kod = mysql_fetch_array ($result)){
echo "<option value=".$kod['KodDaerah'].">" .$kod['NamaDaerah']."</option>
<option value='all'>Seluruh Pahang</option>";
}
echo "<?select>";
?>
The problem is now even when i select a certain KodDaerah, it will just run the provided sql query without using the WHERE statement in the $where. Can anybody help?
EDIT:
$sql = $sql . $where;
$result = mysql_query ($sql);
$BilAkaun = mysql_num_rows ($result);
try to move up the if statement:, remove mysql_real_escape_string
(escape before)
$where = '';
if($KodDaerah != "all"){
$where = "AND maklumatakaun.KodDaerah = '$KodDaerah' "; //Add your where statement here
//Whatever you want to do
}
else {
$where = "";
}
$sql= "SELECT * FROM maklumatakaun
LEFT JOIN detailakaun ON maklumatakaun.id = detailakaun.id
LEFT JOIN maklumatbilakaun ON maklumatakaun.NoAkaun = maklumatbilakaun.NoAkaun
LEFT JOIN kodjenisakaun ON detailakaun.KodJenisAkaun = kodjenisakaun.KodJenisAkaun
LEFT JOIN kodlokasi ON detailakaun.KodLokasi = kodlokasi.KodLokasi
LEFT JOIN kodkategori ON maklumatakaun.KodKategori = kodkategori.KodKategori
LEFT JOIN koddaerah ON maklumatakaun.KodDaerah = koddaerah.KodDaerah
WHERE maklumatakaun.KodKategori = '$KodKategori'
AND detailakaun.KodJenisAkaun = '$KodJenisAkaun'
AND maklumatbilakaun.BulanBil = '$BulanBil'
AND maklumatbilakaun.TahunBil ='$TahunBil'
".$where."
ORDER BY koddaerah.NamaDaerah ";
and then do not append $where again
$result = mysql_query ($sql);
$BilAkaun = mysql_num_rows ($result);