I'm trying to exclude certain rows with a PDO query but it is not returning the right value and I'm not seeing my error maybe some of you can help me.
This is the first query that works.
$objGetRecievedChat = $objDatabaseMessages->prepare('SELECT * FROM messages WHERE recieverid = :recieverid GROUP BY chatid');
Now I want to exclude the chatid's that I get from this query.
foreach ($getRecievedChatFtch as $chatid) {
echo $chatid['chatid'] . '<BR>';
}
When I echo the above I get the next result:
20920
81586
Wich is correct I want to exclude those two values so I execute the next query:
$objGetSendChat = $objDatabaseMessages->prepare('SELECT * FROM messages WHERE ownerid = :ownerid AND chatid != :chatid GROUP BY chatid');
foreach ($getSendChat as $key ) {
echo $key['chatid'] . '<BR>';
}
But when I echo the above I get the next values
44495
20920
44495
this value 44495 is correct although I only need it once (that is why I GROUP BY chatid) But the value 20920 is one of the values I need to exclude.
Does anyone know what I'm doing wrong?
Thanks in advance!
Whole code:
//Voor de berichten die je hebt ontvangen.
$objGetRecievedChat = $objDatabaseMessages->prepare('SELECT * FROM messages WHERE recieverid = :recieverid GROUP BY chatid');
$objGetRecievedChat->bindParam('recieverid', $member_id);
$objGetRecievedChat->execute();
$getRecievedChatFtch = $objGetRecievedChat->fetchAll(PDO::FETCH_ASSOC);
//Dit is voor verzonden berichten.
foreach ($getRecievedChatFtch as $chatid) {
echo $chatid['chatid'] . '<BR>';
$objGetSendChat = $objDatabaseMessages->prepare('SELECT * FROM messages WHERE ownerid = :ownerid AND chatid NOT IN(:chatid) GROUP BY chatid');
$objGetSendChat->bindParam('ownerid', $member_id);
$objGetSendChat->bindParam('chatid', $chatid['chatid']);
$objGetSendChat->execute();
$getSendChat = $objGetSendChat->fetchAll(PDO::FETCH_ASSOC);
foreach ($getSendChat as $key) {
echo $key['chatid'] . '<BR>';
}
}
Change query to catid NOT IN (xxxx,xxxx).
You're making it wrong: in your foreach loop, you retrieve ALL rows BUT the current one. You must put the query out of the foreach and use a WHERE IN
//Voor de berichten die je hebt ontvangen.
$objGetRecievedChat = $objDatabaseMessages->prepare('SELECT * FROM messages WHERE recieverid = :recieverid GROUP BY chatid');
$objGetRecievedChat->bindParam('recieverid', $member_id);
$objGetRecievedChat->execute();
$getRecievedChatFtch = $objGetRecievedChat->fetchAll(PDO::FETCH_ASSOC);
//Dit is voor verzonden berichten.
$chatids = array();
foreach ($getRecievedChatFtch as $chatid) {
echo $chatid['chatid'] . '<BR>';
$chatids = $chatid['chatid'];
}
$placeholders = implode(',', array_fill('?', count($chatids)));
$objGetSendChat = $objDatabaseMessages->prepare('SELECT * FROM messages WHERE ownerid = ? AND chatid NOT IN(' . $placeholders . ') GROUP BY chatid');
$objGetSendChat->execute(array_merge(array($ownerid, $chatids)));
$getSendChat = $objGetSendChat->fetchAll(PDO::FETCH_ASSOC);
foreach ($getSendChat as $key) {
echo $key['chatid'] . '<BR>';
}
More or less (because I dislike using WHERE IN with prepared statement. You usually can avoid them with JOIN.
$objGetSendChat = ...
While you use $getSendChat in the foreach.
So I feel we're missing some code here, that contains the error.
Plus, you do a GROUP BY chatid and you get 44495 twice in the result, so the result cannot be the query's one.
Related
Ok so what i am doing is getting member id's from 1 table and looping those ID's through another table to get values to output. I had it working going through the first loop, then notice the output was all screwy, so released I needed to loop it through again, since there will could be multiple entries in the 2nd query for MemID. now I put in the 2nd loop but its not even going through, not sure where I messed up the code, but doesn't seem to output now when running it through the 2nd loop. though it did output without the loop. but that won't work due to multiple rows for each $memid.
$qry_skamembers = "SELECT * FROM ap_skamembers ORDER BY id";
$qry_skamembers = $mysqli->real_escape_string($qry_skamembers);
if($result_skamembers = $mysqli->query($qry_skamembers)){
while($row_skamembers = $result_skamembers->fetch_array()){
$AffID = $row_skamembers['AffID'];
$MemID = $row_skamembers['MemberID'];
$skacon = new mysqli(OW_DB_HOST, OW_DB_USER, OW_DB_PASSWORD, OW_DB_NAME);
if ($skacon->connect_error) {
die('Connect Error');
}
$get_data = "SELECT * FROM ow_base_billing_sale WHERE userID = $MemID AND status = 'delivered' ORDER BY id";
$get_data = $skacon->real_escape_string($get_data);
if($result_data = $skacon->query($get_data)){
while($finish = $result_data->fetch_array()){
$test = $finish['status'];
if($test == 'delivered') {
$sale_amount = $finish['price'];
$product = $finish['transactionUId'];
$products = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM ap_earnings where product = $product"));
if(mysqli_num_rows($products) > 0) { }
else {
echo "AFF: " . $AffID . " | ";
echo "Mem: " . $MemID . " | ";
echo "PRICE: " . $sale_amount . " | ";
echo "PRODUCT: " . $product . " -- ";
include('controller/record-sale.php');
echo "inserting record";
echo "run finished <br><br>";
}
}
}
}
}
}
I am still rather new at coding, so it might look a bit sloppy, my apologies for that.
I do not know if that is ist bu try to replace:
$get_data = $skacon-->real_escape_string($get_data);
with
$get_data = $skacon->real_escape_string($get_data);
i think there is an extra -
And as we found out in comments you need to change $product to '$product'
You can do all that in one query,nevermind it will be much faster
SELECT aps.AffID,aps.MemberID,owb.price,owb.transactionUId
FROM db1.ap_skamembers aps JOIN db2.ow_base_billing_sale owb
ON aps.MemberID = owb.userID AND owb.status='delivered'
JOIN db3.ap_earnings ape
ON ape.product = owb.transactionUId
ORDER BY aps.id
I know this may seem like a duplicated, out of stackoverflow, etc question but here we go.
I'm trying to make an SQL sentence that can find a coincidence between two strings
function getProductos($keyWords){
$keyWords = addslashes(strtolower($keyWords));
$keyWordsExploded = explode(" ",$keyWords);
$sql = "SELECT * FROM PRODUCTOS WHERE HOMBRE_MUJER LIKE :keyWords OR CATEGORIA LIKE :keyWords" OR NOMBRE LIKE :keyWords;
$query = self::$conn->prepare($sql);
$query->execute(array(":keyWords"=> "%" . $keyWords . "%"));
return $query;
}
In other part of the page I have this code:
<?php
if(isset($_GET['buscar'])){
require(PAGES_DIR . "queries_products.php");
$consultaProducts = new QueryProductos();
$productos = $consultaProducts->getProductos($_GET['buscar']);
if($productos->rowCount()!=0){
$arrayProductos = $productos->fetchAll(PDO::FETCH_ASSOC);
echo "<h3>Productos encontrados</h3>";
foreach($arrayProductos as $fila){
echo $fila['NOMBRE'] . " " . $fila['HOMBRE_MUJER'] . "<br>";
}
}else{
echo "<p class='alert alert-warning'>No results found <strong>" . $_GET['buscar'] . "</strong>";
}
}
?>
Everything works fine, In my database I store only 2 values in CATEGORIA which are: "hombres" and "mujeres", if i search for hombres I get all records which have a CATEGORIA of hombres but when i search for hombres y mujeres I get no results, I have tried using different sentences that i read but I haven't had any luck, I hope you can greatly save me by helping me solve this problem.
try this:
function getProductos($keyWords) {
$keyWordsExploded = explode(" ",$keyWords);
$sql = "SELECT * FROM PRODUCTOS WHERE ";
$likes = array("HOMBRE_MUJER", "CATEGORIA", "NOMBRE"); // build up our columns which will be used in our condition in sql statment
$params = array();
// building up our sql statment and collecting our params
foreach($likes as $like) {
foreach($keyWordsExploded as $kw) {
$sql .="$like like ? or ";
$params[] = "%".$kw."%";
}
}
$sql = rtrim($sql, "or "); // trim the last "or" condition in sql statment
$query = self::$conn->prepare($sql);
$query->execute($params);
return $query;
}
I have a MySQL query that requests a list of items.
I fetch for them and want to display every item with a for loop, but it shows me just the first item repeated, instead of every item.
Why?
<?php
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$query = " SELECT cursoID, nombreCurso, estadoCurso
FROM cursos
WHERE estadoCurso='abierto'";
$buscarCurso = mysqli_query($conectar,$query);
$curso=mysqli_fetch_assoc($buscarCurso);
$totalRows = mysqli_num_rows($buscarCurso); //There are 3 rows of results
echo $totalRows;
for ($i=0; $i < $totalRows; $i++) {
echo '<br>';
echo $curso['nombreCurso'];
echo '<br>';
}
?>
The intended result is:
Curso 1
Curso 2
Curso 3
And instead I get
Curso 1
Curso 1
Curso 1
Your loop should be fetching from the result set on every iteration. The standard way (as in many examples given in the PHP documentation) is that you do this in the while condition:
$totalRows = mysqli_num_rows($buscarCurso); //There are 3 rows of results
echo $totalRows;
while ($curso=mysqli_fetch_assoc($buscarCurso)) {
echo '<br>';
echo $curso['nombreCurso'];
echo '<br>';
}
You need a loop for the query result. In this case, you'll get just one result and loop through that result 3 times.
<?php
while($curso = mysqli_fetch_assoc($buscarCurso)) {
// Do some stuff
echo '<br />' . $curso['nombreCurso'] . '<br />';
}
?>
First use prepared statement for block SQL injection than check this code
<?php
$conn = mysqli_connect(HOST, USER, PASS, DATABASE);
$select_cursos = $conn->prepare(" SELECT
cursoID, nombreCurso, estadoCurso
FROM cursos
WHERE estadoCurso = ? ORDER BY nombreCurso ASC
");
$select_cursos->bind_param('s', $nombreCurso);
$nombreCurso = 'abierto'; // This you can get from a $_POST too
if (!$select_cursos->execute()) { // ERROR
echo('Error');
} else { // OK
$select_cursos_result = $select_cursos->get_result();
$select_cursos_count = select_cursos_result->num_rows;
echo('Found: '.$select_cursos_count);
if ($select_cursos_count > 0) {
while ($data = $select_cursos_result->fetch_assoc()) {
echo ($data['nombreCurso'].'<br>');
}
} else {
echo ('No data!!');
}
}
?>
Cheers!!!
I have an array of Information States And Totals. I want to see how to get the Total of all the Totals for each state.
I know I have to use a loop but I am not sure which - what would I do?
This is what I have so far. It's making the array from a database.
$WorkFind = mysql_query(
"SELECT Customers.State, WorkOrders.Total
FROM WorkOrders
INNER JOIN Customers
ON WorkOrders.CID=Customers.ID
WHERE WorkOrders.Type <> 'Warranty'
AND (WorkOrders.Status <> 'Closed'
OR WorkOrders.Status <> 'Cancelled')
AND WorkOrders.TransferID='0'
ORDER BY Customers.State ASC");
while ($Work = mysql_fetch_array($WorkFind)) {
}
The while loop has made the array but I'm unsure what to put into it.
I'm using PHP 5.3 and MYSQL 5.2
Try this:
$WorkFind = mysql_query("SELECT Customers.State AS State, WorkOrders.Total AS Total -- ...");
$total = array();
while ($Work = mysql_fetch_array($WorkFind)) {
$state = $Work['State'];
if (!isset($total[$state])) {
$total[$state] = 0;
}
$total[$state] += $Work['Total'];
}
// format as simple table
echo '<table><tr><th>State</th><th>Total</th></tr>';
foreach ($total as $state_name => $state_total) {
echo '<tr><td>' . $state_name . '</td><td>' . $state_total . '</td></tr>';
}
echo '</table>';
I need to be able to display the course_desc on line 30, beside the course_name.
<?php
$result = $db->query("select distinct c.dbid, c.course_name, c.course_image, m.module_id, m.module_name, m.module_name_id, m.module_image, m.hasFiles, m.files from courses c join modules_to_courses mc on (c.dbid = mc.courses_id) join modules m on (mc.modules_id = m.module_id)");
$course_name = $db->query("SELECT distinct course_name, course_desc FROM courses");
while ($temp = $course_name->fetch_assoc()) {
$courses[] = $temp['course_name'];
}
$final = array();
// Retrieve results
while ($row = $result->fetch_assoc()) {
// Add to final array via counter if valid course is found
if (in_array($row['course_name'], $courses)) {
$final[$row['course_name']][] = $row;
}
}
// Display if final array is not empty
if (!empty($final)) {
// Loop through each potential course name
foreach ($courses as $name) {
// Output if the course has values within the final array
if (array_key_exists($name, $final)) {
echo '<div>'."\n";
echo ' '. $name . "\n";
echo '<!-- list of modules -->'."\n";
// Loop through internal values
foreach ($final[$name] as $value) {
$module_name = $value['module_name'];
echo ' '. $module_name ."\n";
}
echo ' </div>'."\n";
}
}
}
?>
You already having your course description in $final so you can access it using,
$final[$name]['course_desc']
I have created a paste based on your with changes. Also note that it's need to change your $final array.
distinct course_name, course_desc means you are trying to fetch the values regarding to distinct course_name and distinct course_desc together. You may wanna use group by instead. If I understood correctly, your statement will not bring you distinct course names and their related course desc. (if that is what you want)