Wordpress and SQL, compare condition - php

I wanna compare "postType",
<input name="postType" value="" id="postType" required>
with a column in my DB called "post_type" (from table wp_posts). So, I just wanna the results with matches the input with the value in post_type column. I don't know if I can do a for each or put a SQL statement. Examples:
if($_POST["postType"] == "page") {
//results
}
So, if I put "page" in my input it returns the correct results.
What I've done to the general case:
$term = $_POST["postType"];
$result = $wpdb->get_results("SELECT count(ID) FROM $wpdb->posts WHERE post_type = '".$term."')");
foreach($result as $resultX) {
if($_POST["postType"] == $resultX) {
//results
}
}
But it is not working

Related

How do I list each value from my_sqli_fetch_row?

I have two sql statements.
1 lists all columns from my table using mysqli_fetch_assoc
The other statements returns a row where id = specific id using mysqli_num_rows
My problem is that with the mysqli_fetch_assoc, I'm able to use something like:
$rowz['Field'] and it returns the value for every single column name. This is perfect, but, I am unable to get every single value in my row as well. In other words, My code lists all fields: id / name / phone... but when I use myqli_fetch_row, it returns the value for just one column over and over. So every field will just show '193' which is the id. I want all fields to show proper value instead of just the same value from one column over and over.
// listing all columns from table
$sql2 = ("SHOW COLUMNS FROM articles");
$result55 = mysqli_query($link, $sql2);
echo'<form action="update.php" method="POST">';
if (mysqli_num_rows($result55) > 0)
{
// to fetch row of specific id
$sql = "SELECT * FROM articles WHERE ID='".$id."'";
$result5 = mysqli_query($link, $sql);
if (!$result5) {
echo 'no';
}
$row = mysqli_fetch_row($result5);
while($rowz = mysqli_fetch_assoc($result55)){
$z = 0;
echo '
<input class="form-control" type="text" name="'.$rowz['Field'].'"
value="'.$row[$z].'" />';
}
}
echo' </form>';
The issue is the name of the input field, where I have '.$row[$z].' it just keeps returning 0 from array which is just the ID column. Hence why I just keep getting 193 over and over. However, the $rowz['Field'] works much better and loops every single time for each existing column. I hope to get: id = 193, name = john, phone = 123-3345 etc.. But instead I get: id = 193, name = 193, phone = 193.
Please send help!
$z is your column index. and it should be your counter, if you want to generate each column values.
$z = 0;
while($rowz = mysqli_fetch_assoc($result55)){
echo '
<input class="form-control" type="text" name="'.$rowz['Field'].'"
value="'.$row[$z].'" />';
$z = $z + 1;
}
You have declared $z=0 inside the while loop.
Rather you have to declare it before the while loop and increment it inside the loop.
You have used $z as the index for $row which indicates the specific column of the result obtained from the query.
When you fix it to 0, it means that the first column value only is getting accessed.
$row = mysqli_fetch_row($result5);
$z=0;
while($rowz = mysqli_fetch_assoc($result55))
{
echo '
<input class="form-control" type="text" name="'.$rowz['Field'].'"
value="'.$row[$z].'" />';
$z = $z +1;
}

How to check all values present in the column 'pincode'?

This code only reads the first value present in the column. If the value posted in the html form matches the first value, it inserts into the database. But I want to check all the values in the column and then take the respective actions.
For example, if i give input for 'ppincode' and 'dpincode' as 400001, it accepts. but if i gave 400002, 400003,..... it displays the alert even if those value are present in the database
DATABASE:
pincode <== column_name
400001 <== value
400002
400003
400004
...
also i tried this
$query = "SELECT * FROM pincodes";
$result = mysqli_query($db, $query);
$pincodearray = array();
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)){
$pincodearray[] = $row;
}
}
If I understand well - you want to compare value from POST request with all retrieved records saved in DB and if it matches - perform action.
If so, I would recommend using for(each) loop. Example:
if( !empty($row){
foreach( $row as $key ){
if($key['pincode'] == $ppincode && $key['pincode'] == $dpincode){
// your action goes here
}
}
}
Additional tip: use prepared statements :)
SELECT count(*) FROM table WHERE ppincode=ppincode AND bpincode=bpincode
if this return 0 then insert or else show alert.

php foreach loop search mysql table with several words

I have a mysql table called foods with columns "id, name, addinfo, picname, mg1cup, mg100g". I have a form where the user can submit between 1-20 food names. The php file takes the submitted food names in an array called $terms[]. I need to search the sql table for all terms and return results for all columns for each of the terms.
However, the results are only showing the first term submitted, repeated as many times as there are inputs (for example, if two words were inputted, the first term gets outputted in the results twice - instead of first word results, then second word results).
I don't know what I'm doing wrong. Here's my code (I haven't added the function to sanitize the strings yet):
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//connect to the wordpress (bluehost)DB
require_once '../../../wp-config.php';
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Could not connect to mysql');
$Db = mysql_select_db(DB_NAME, $link) or die('Could not select database.');
//check to see if the search term has a value, matches "name" column in DB, and if so, put it into an array called terms
if (isset($_POST['terms'])) {
$terms = ($_POST['terms']);
if (count($terms) > 0 ) {
$results=array();
foreach($terms as $term) {
$sql = 'SELECT * from `wpqr_foods` WHERE `name` like "%'. $term .'%" ORDER BY name ASC';
$Q1 = mysql_query($sql);
if(mysql_num_rows($Q1)) {
while ($Res = mysql_fetch_assoc($Q1)) {
$results[] = $Res;
}
}
//$results = mysql_query($sql);
$sql = 'SELECT * from wpqr_foods WHERE name LIKE "%'. $term .'%" ORDER BY name ASC';
$Q2 = mysql_query($sql);
//get results
if(mysql_num_rows($Q2)) {
while ($Res = mysql_fetch_assoc($Q2)) {
$results[] = $Res;
}
}
}
if (count($results) > 0 ) {
foreach ($results as $CurRes ) {
echo $CurRes['name']. "<br/>";
echo $CurRes['addinfo']. "<hr/>";
/*
[id] => 5
[name] => Apples
[value] => Yes
[addinfo] => They can eat apples. They can also eat the skin of the apple and the leaves of the apple tree, but the tree leaves are high in calcium, so limit their intake. They can also chew on the apple tree branches.
[picname] => apple
[mgc1cup] => 5.8
[mgc100g] => 4.6
*/
}
}
else {
echo "(nothing entered)";//MEANS $TERM IS EMPTY
}
}
else {
echo "(nothing entered)";//means $_POST IS NOT SET (end of if(isset($_POST['term'])) { )
}
}
//function to sanitize array values from form
function sanitizeString($var) {
if (is_array($val))
{
foreach ($val as $k => $v)
{
$val[$k] = htmlentities(strip_tags($v),ENT_QUOTES);
}
}
else
{
$val = htmlentities(strip_tags($terms),ENT_QUOTES);
}
return $val;
}
?>
The HTML is
<div class="my-form">
<form role="form" id="step1" method="post" action="/wp-content/themes/mia/vitcdata.php">
<p class="text-box"><label for="box1">Food <span class="box-number">1 </span></label><input type="text" name="terms[]" value="" placeholder="apples" id="box1" /> <a class="add-box" href="#">Add More</a></p>
<p><input type="submit" value="Submit" /></p>
</form>
The form has dynamic form fields which users can add via javascript, and they can add up to 20 text inputs, in which all inputted terms get added to the $terms[] array.
So, if I test it, use two fields, and input "apples" and "bananas", the results show all the data for "apples" repeated twice.
Check this, you can check a related question here:
Using OR in LIKE Query in MySQL to compare multiple fields
You might have to do something like this in your query.
$sql = 'SELECT * from wpqr_foods WHERE name LIKE "%'. $term .'%" OR addinfo LIKE "%'. $term .'%" ORDER BY name ASC';
OR,
$sql = 'SELECT * FROM `wpqr_foods` WHERE CONCAT(name, addinfo ) LIKE "%'. $term .'%" ORDER BY name ASC';
I would recommend the following two ways forward:
It looks like the code block that queries the database and pushes results into $results is duplicated. You probably want to get rid of the duped block as that will create 2x results for each distinct term.
I suspect what's actually getting passed to the server through the form is a string containing whitespace-separated (or commas, or whichever separator the user chose to enter) terms. Even though you've chosen to pass it (and receive it server-side) as an array, it is actually a string and you will have to explode it (or some other method) yourself into an array. To check if that's the case (and if you haven't do so already), somewhere inside the foreach ($terms as $term) loop you should inspect $term to see if it is what you expect it to be.

Switch Statement based on if variables in two tables match

So I have a switch statement that I want to display one form or another based on if the id from one table has the matching foreign key in another table.
So far what I have tried is nesting one while statement into another which isn't working.
$subresult = mysqli_query($con,"SELECT * FROM tags GROUP BY tag");
$subresult2 = mysqli_query($con,"SELECT * FROM tag_subscribe WHERE uid = $uid");
while ($row = mysqli_fetch_array($subresult)) {
$tid = $row['tid'];
while ($row2 = mysqli_fetch_array($subresult2)) {
$tid2 = $row2['tid'];
}
if ($tid2 == $tid) {
$subbedup = 'yes';
} else {
$subbedup = 'no';
}
switch ($subbedup) {
case ('yes'):
echo "alternate html form goes here because $tid2 == $tid";
break;
case ('no'):
echo "html form goes here";
break;
}
}
So when this code is run, it only returns switch "no" except it will return one switch "yes" which just happens to be the last record of the second table that contains the foreign key. When I think about it, that makes sense as it will just keep running through this loop until it runs out of records in the table. So I spent about six minutes getting to this point and I have spent the last 6 hours trying to get it to work correctly without any luck.
So once again, fine people at SO, save me! Please and Thank you :)
So my question is: How would this be done correctly?
I'm not exactly sure of your database structure, so I'll improvise.
Given these sample tables and columns:
tags
id name
tag_subscriptions
user_id tag_id
The query below will loop through all tags. Each tag includes a subscribed column set to either "yes" or "no", depending on whether the current user is subscribed to that particular tag.
$sql="SELECT t.`id`, t.`name`, IF (ISNULL(ts.`tag_id`),'no','yes') AS `subscribed`
FROM `tags` t
LEFT JOIN `tag_subscriptions` ts ON (ts.`user_id`=$uid AND ts.`tag_id`=t.`id`)
WHERE 1;"
Then loop through all tags:
$q=mysql_query($sql) or die(mysql_error());
while ($row=mysql_fetch_assoc($q)) {
switch ($row['subscribed']) {
case 'yes'
// user is subscribed to this tag
break;
default:
// user is not subscribed to this tag
}
}
I think (hope) this is closer to what you're looking for.
http://sqlfiddle.com/#!2/58684/1/0
Sorry for using PDO as thats what i know, you can convert the idea to MYSQLi im sure.
$db = new PDO($hostname,$username,$password);
$arraySubTags = array();
$query = "SELECT tagID FROM tag_subscribe WHERE uid = :uid";
$statement = $db->prepare($query);
$statement->bindValue(':uid', $uid);
$statement->execute();
$subscribedTags = $statement->fetchAll(PDO::FETCH_ASSOC); //or loop with a while using fetch()
$statement->closeCursor();
foreach($subscribedTags as $sTag)
{
array_push($arraySubTags,$sTag);
}
$query = "SELECT * FROM tags GROUP BY tag";
$statement = $db->prepare($query);
$statement->execute();
$allTags = $statement->fetchAll(PDO::FETCH_ASSOC); //or loop with a while using fetch()
$statement->closeCursor();
foreach($allTags as $tag)
{
if(in_array($tag['tagID'], $arraySubTags))
{
echo "person is subscribed";
}else{ echo "person not subscribed";}
}
This code just checks whether the last tag checked is subscribed to - to check for each one you need to move the switch statement into the outer while loop, after the if..else bit that sets the $subbedup variable for the current tag.
Or you could make $subbedup an array, indexed by the tag id, if you need to keep the switch separate for some reason.

PHP - SQL select first column with no data

How do I find the first column with no data?
//column pet1='dog'
//column pet2=''
//column pet3=''
//column pet4='cat'
if($F=="getempty"){
$uid=$_GET["uid"];
$sql = mysql_query("SELECT DISTINCT pet1,pet2,pet3,pet4 FROM a WHERE uid='".$uid."' AND pet1='' OR pet2='' OR pet3=''OR pet4=''");
while($column=mysql_fetch_field($sql)){
$empty=$column->name;
echo json_encode(array("empty"=>$empty));
}
}else{}
I keep trying but so far it just returns all column names if one is empty
pet1,pet2,pet3,pet4
DISTINCT will combine the rows which are exactly alike (having all the selected columns the same) and return them.
To get the name of the first empty column, use a query like:
SELECT
CASE
WHEN pet1 = '' THEN 'pet1'
WHEN pet2 = '' THEN 'pet2'
WHEN pet3 = '' THEN 'pet3'
WHEN pet4 = '' THEN 'pet4'
ELSE NULL
END AS firstempty
FROM a
WHERE uid = '$uid';
The idea is that the CASE statement checks each one in order, and finding an empty one returns the column name without checking the rest of them.
Don't forget to escape $uid with mysql_real_escape_string() before passing it to the query.
$uid = mysql_real_escape_string($uid);
Since we're now getting the column name inside a field called firstempty, we'll also need to change the way it's fetched:
while($row = mysql_fetch_assoc($sql)){
$empty = $row['firstempty'];
echo json_encode(array("empty"=>$empty));
}

Categories