I have a query that should check input order number, first name and post number and check if they match what is in the wordpress database, but the query always goes through no matter what post number I input, the code itself looks like this:
// Taking the user input into variables
$ordernumber = $_POST['ordernmbr'];
$orderfirstname = $_POST['firstname'];
$orderpostnumber = $_POST['postnmbr'];
$page = $_POST['page'];
// Sanitizing
$ordernumber = stripslashes_deep($ordernumber);
$orderfirstname = stripslashes_deep($orderfirstname);
$orderpostnumber = stripslashes_deep($orderpostnumber);
// Query that searches for order data from db
$sql = $wpdb->prepare("SELECT post_id FROM wp_postmeta
WHERE post_id = %d AND meta_key in ('_billing_first_name', '_billing_postcode')
and meta_value in ('%s', '%d' )
group by post_id", $ordernumber, $orderfirstname, $orderpostnumber);
$res = $wpdb->get_results($sql, ARRAY_A);
What am I missing so that the post number would also be required to be correct
Related
I'm trying to create a filter in DataTables, but what I found is only filtering the data in "front end" (in the datatables script). I have 10K rows in the SQL table so I think, the "front end filtering/searching" is not my best option. I need to create a filter to my SQL Query in server-side, and get back only the filtered rows (datas).
Also the search option is not good option for me because I have in tables values like 1 or 2 (boolean).
My DataTables using this method (way) of fetching datas from SQL in backend:
include 'config.php';
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = $_POST['search']['value']; // Search value
$searchArray = array();
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " AND (emp_name LIKE :emp_name or
email LIKE :email OR
city LIKE :city ) ";
$searchArray = array(
'emp_name'=>"%$searchValue%",
'email'=>"%$searchValue%",
'city'=>"%$searchValue%"
);
}
## Total number of records without filtering
$stmt = $conn->prepare("SELECT COUNT(*) AS allcount FROM employee ");
$stmt->execute();
$records = $stmt->fetch();
$totalRecords = $records['allcount'];
## Total number of records with filtering
$stmt = $conn->prepare("SELECT COUNT(*) AS allcount FROM employee WHERE 1 ".$searchQuery);
$stmt->execute($searchArray);
$records = $stmt->fetch();
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$stmt = $conn->prepare("SELECT * FROM employee WHERE 1 ".$searchQuery." ORDER BY ".$columnName." ".$columnSortOrder." LIMIT :limit,:offset");
// Bind values
foreach($searchArray as $key=>$search){
$stmt->bindValue(':'.$key, $search,PDO::PARAM_STR);
}
$stmt->bindValue(':limit', (int)$row, PDO::PARAM_INT);
$stmt->bindValue(':offset', (int)$rowperpage, PDO::PARAM_INT);
$stmt->execute();
$empRecords = $stmt->fetchAll();
$data = array();
foreach($empRecords as $row){
$data[] = array(
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"gender"=>$row['gender'],
"salary"=>$row['salary'],
"city"=>$row['city']
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);
In this code as you can see I have Search option, but as I said I can't use it for filtering columns with boolean values for example.
Another example what I want to do:
I have a column named by "edited" with boolean values.
How can I get those rows where the column "edited" have values 0?
I'm using MariaDB.
Thank you for your help!
You can easy write ...WHERE edited = :edited ... the value of edited should be 0 for false and 1 for true.
So in your example:
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " AND (emp_name LIKE :emp_name or
email LIKE :email OR
city LIKE :city ) AND
edited = :edited";
$searchArray = array(
'emp_name'=>"%$searchValue%",
'email'=>"%$searchValue%",
'city'=>"%$searchValue%",
'edited'=>$edited
);
}
I am trying to do an update query in php to update my database but the query is not working. It is probably something simple.
$query = "UPDATE Events
SET charity_name = '$charity_name' ,
charity_reg = $charity_reg ,
Event_Name = '$event_tit',
Event_Status_Code = '$event_stat',
Start_Date = $event_dat,
Hours = $event_hour,
location = '$event_loc',
Other_Details = $event_content,
event_image = $imageData,
image_name = '$imageName',
max_available_spaces = $event_spaces,
Event_type = '$eve_category',
event_cost = $event_cost,
event_organiser = '$event_organiser'
WHERE Event_ID = $the_event_id";
You are not putting quotes ('') around some values, that might be a problem unless all thoses values are boolean/ints. Make sure to put quotes around all values, like '$imageData' instead of $imageData Also watch out for sql injections when you are directly inputting the values in your query. Better to use prepared statements
$query = "UPDATE Events
SET charity_name = '$charity_name' ,
charity_reg = '$charity_reg' ,
Event_Name = '$event_tit',
Event_Status_Code = '$event_stat',
Start_Date = '$event_dat',
Hours = '$event_hour',
location = '$event_loc',
Other_Details = '$event_content',
event_image = '$imageData',
image_name = '$imageName',
max_available_spaces = '$event_spaces',
Event_type = '$eve_category',
event_cost = '$event_cost',
event_organiser = '$event_organiser'
WHERE Event_ID = $the_event_id;";
EDIT: as #dWinder mentioned: if $the_event_id is not an integer, make sure to also put quotes around that value.
I am trying to create a check-in/check-out table in my database. My check-in form works without issue, inserting the time into my database. The problem occurs when I try to check out. Everything is good on the first entry...
But when I try to check in and check out again, this happens...
So far so good, but when I check out...
Currently, my code updates the out column and totalTime column of all matching child_id's.
Here is my code:
// Select the correct child from the database
$sql_childID = "SELECT id FROM child
WHERE firstName = '$childFirstName'
AND lastName = '$childLastName'";
$result = $pdo->query($sql_childID);
$row = $result->fetch();
$var = $row['id'];
// Insert the check out time for the child
$query = "UPDATE checkinout
SET `out` = :nowTime
WHERE child_id = $var
AND `in` IS NOT NULL";
$statement = $pdo->prepare($query);
$statement->bindValue(':nowTime', date("YmjHis"));
$statement->execute();
// Select check in time for specified child
$sql_inTime = "SELECT `in` FROM checkinout
WHERE child_id = $var";
$inResult = $pdo->query($sql_inTime);
$inRow = $inResult->fetch();
$inTime = strtotime($inRow['in']);
// Select the check out time for specified child
$sql_outTime = "SELECT `out` FROM checkinout
WHERE child_id = $var";
$outResult = $pdo->query($sql_outTime);
$outRow = $outResult->fetch();
$outTime = strtotime($outRow['out']);
// Find total hours
$totalTime = abs($outTime - $inTime)/(60*60);
// Update totalHours column for specified child
$queryTotalTime = "UPDATE checkinout
SET totalTime = :totalTime
WHERE child_id = $var
AND 'out' IS NOT NULL";
$statement = $pdo->prepare($queryTotalTime);
$statement->bindValue(':totalTime', $totalTime);
$statement->execute();
I think you could do all of this in your first update statement using TIMESTAMPDIFF rather than figuring the total time with PHP:
UPDATE checkinout
SET
out = NOW(),
totalTime = TIMESTAMPDIFF(SECOND, `in`, NOW()) / 3600
WHERE
child_id = $var
AND out IS NULL
The criteria WHERE out IS NULL will only update rows that do not have a value in the out column yet.
IF you have MySQL Db THEN sql will be
SELECT TIMESTAMPDIFF(HOUR,in,out) from checkinout;
I am trying to do this by 2 hours.
I have custom fields in database and I want to get post_id by the meta keys or meta values.
I am doing like this
$post_id = $wpdb->get_var("SELECT post_id FROM $wpdb->postmeta WHERE (meta_key = 'mfn-post-link1' AND meta_value = '". $from ."')");
print_r($post_id); // giving only 140
this is working fine, but this is giving only one post_id and I want all possible post_id matched by meta_value.
for example :
I have three post 140,141,142, in database. But by this query I am only getting 140.
Any Idea how to get all possible post_id by this query or any other way by comparing meta_fields...
Thanks
$post_id = $wpdb->get_results("SELECT post_id FROM $wpdb->postmeta WHERE (meta_key = 'mfn-post-link1' AND meta_value = '". $from ."')");
print_r($post_id); /
$post_id = $wpdb->get_results("SELECT post_id FROM $wpdb->postmeta WHERE (meta_key = 'mfn-post-link1' AND meta_value = '". $from ."')");
print_r($post_id);
for more information ... http://codex.wordpress.org/Class_Reference/wpdb
<?php
$user_id = 1;
global $wpdb;
$wpdb_prefix = $wpdb->prefix;
$wpdb_tablename = $wpdb_prefix.'Table_Name';
$result = $wpdb->get_results(sprintf('SELECT `colum1`, `colum2` FROM `%2$s` WHERE `user_id` = %d LIMIT 1', $user_id, $wpdb_tablename));
print_r($result); exit;
?>
I'm trying to create an API and I need to put multiple queries into my JSON ouput, the issue is everything is returned as an object of class stdClass... here is my code:
$querystr = "SELECT entry_id AS id FROM {$wpdb->prefix}connections_term_relationships WHERE term_taxonomy_id = '{$_GET['catID']}'";
$cID = $wpdb->get_results($querystr);
$dirCount=count($cID);
$arrayCategory= array();
$androidArray = array();
if($dirCount > 0){
foreach($cID as $company){
$querycInfo = "SELECT id, organization, contact_first_name, contact_last_name, bio FROM {$wpdb->prefix}connections WHERE id = '{$company->id}'";
$companyInfo = $wpdb->get_row($querycInfo);
$queryAddress = "SELECT line_1, line_2, line_3, state, zipcode FROM {$wpdb->prefix}connections_address WHERE entry_id = '{$company->id}'";
$address = $wpdb->get_row($queryAddress);
$queryEmail = "SELECT address FROM {$wpdb->prefix}connections_email WHERE entry_id = '{$company->id}' AND type = 'work'";
$email = $wpdb->get_row($queryEmail);
$queryWebsite = "SELECT title, url FROM {$wpdb->prefix}connections_link WHERE entry_id = '{$company->id}' AND type = 'website'";
$website = $wpdb->get_row($queryWebsite);
$queryPhone = "SELECT number FROM {$wpdb->prefix}connections_phone WHERE entry_id = '{$company->id}' AND type = 'workphone'";
$phone = $wpdb->get_row($queryPhone);
$arrayCategory[]= $companyInfo;
}
}else{
$arrayCategory[0]=array('organization'=>'No Company Found Within This Category');
}
$androidArray = array('companies'=>$arrayCategory);
echo json_encode($androidArray);
}
I need $arrayCategory to hold more then just $companyInfo, I need it to hold the other variables as well. This is being built for WordPress. Thanks in advance!
I ended up just formatting my SQL query in a matter that made more sense:
$querycInfo = "SELECT main.id, organization, contact_first_name, contact_last_name, bio, number FROM {$wpdb->prefix}connections main
JOIN {$wpdb->prefix}connections_phone phone ON phone.entry_id = main.id AND main.id = '{$company->id}'";
This solved the issue.