I asked this question in http://codereview.stackexchange.com and they wanted me to post it here. I couldn't get this code to work at all. I switched from regular mysql to pdo which is more safer. Could someone tell me what I'm missing here. I've been struggling with it for couple of day, and I could find exact answer when I first searched this site.
$input = $_POST['input'];
$categories = $_POST['category'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$qq = $db->prepare(" SELECT * FROM classified ")or die(print_r($qq->errorInfo(), true));
/*** execute the prepared statement ***/
$qq->execute();
/*** echo number of columns ***/
$rows = $qq->fetch(PDO::FETCH_NUM);
if ($rows>0){
$query = (" SELECT * FROM classified ");
$cond = array();
$params = array();
if (!empty($input)) {
$cond[] = "title = ?";
$params[] = $input;
}
if (!empty($categories)) {
$cond[] = "id_cat = ?";
$params[] = $categories;
}
if (!empty($state)) {
$cond[] = "id_state = ?";
$params[] = $state;
}
if (!empty($zipcode)) {
$cond[] = "zipcode = ?";
$params[] = $zipcode;
}
if (count($cond)) {
$query .= ' WHERE ' . implode(' AND ', $cond)or
die(print_r($query->errorInfo(),true));
}
$stmt = $db->prepare($query);
$stmt->execute($params);
$ro = $stmt->fetch(PDO::FETCH_NUM);
}
if ($ro > 0) {
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row)
{
echo $row['title'];
echo $row['categories'];
echo $row['state'];
echo $row['zipcode'];
}
}
I think it's a good idea to post an answer here rather than posting a link. I'm sure it will be useful for some people.
$input = $_POST['input'];
$categories = $_POST['category'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$qq = $db->prepare(" SELECT * FROM classified ")or die(print_r($qq->errorInfo(),
true));
/*** execute the prepared statement ***/
$qq->execute();
/*** echo number of columns ***/
$rows = $qq->fetch(PDO::FETCH_NUM);
if ($rows>0){
$query = " SELECT * FROM classified where confirm='0' ";
if(!empty( $_POST['input'])) {
$query .= "AND title LIKE '%".$input."%' ";
}
if (!empty($_POST['category']) )
{
$query .= "AND id_cat = ".$categories." ";
}
if (!empty($_POST['state']) )
{
$query .= "AND id_state = ".$state." ";
}
if(!empty($_POST['zipcode'])) {
$query .= "AND zipcode = ".$zipcode." ";
}
$query .= "ORDER BY date ";
}
$stmt = $db->prepare($query);
$stmt->execute($params);
$result = $stmt->fetchAll();
// $ro = $stmt->fetch(PDO::FETCH_NUM);
// it didn't work when I tried to count rows
if ($result > 0) {
foreach ($result as $row)
{
echo $row['title'];
echo $row['categories'];
echo $row['state'];
echo $row['zipcode'];
}
}else{
echo " No data available";
}
Related
I am querying from two different tables in the database here and I can store the values from the first query but how do I store the information from the second query?
$query = "SELECT * ";
$query .= "FROM user_account ";
$query .= "WHERE user_id = $user_id ";
$query .= "SELECT * ";
$query .= "FROM user_profile ";
$query .= "WHERE user_id = $user_id ";
if (mysqli_multi_query($mysqli, $query)) {
do {
if ($result = mysqli_store_result($mysqli)) {
while ($row = mysqli_fetch_row($result)) {
$Firstname = $row['Firstname'];
$Lastname = $row['Lastname'];
$Email = $row['Email'];
$Birthday = $row['Birthday'];
$Address = $row['Address'];
$Zip = $row['Zip'];
$City = $row['City'];
$State = $row['State'];
$Country = $row['Country'];
$Avatar = $row['Avatar']; Will be added later
$Phone = $row['Phone'];
$Website = $row['Website'];
$Member_level = $row['Member_level'];
}
mysqli_free_result($result);
}
if (mysqli_more_results($mysqli)) {
}
while (mysqli_next_result($mysqli)) ;
}
}
Just the usual way
$query = "SELECT * FROM user_account WHERE user_id = $user_id ";
$account = $mysqli->query($query)->fetch_assoc();
$query = "SELECT * FROM user_profile WHERE user_id = $user_id ";
$profile = $mysqli->query($query)->fetch_assoc();
as simple as that.
I am really wondering why PHP users are inclined to writing SO MUCH code and to using so much intricate ways for the most trifle operations
On a side note, in your particular case you can write a single JOIN query.
In your code, why are you using mysqli_free_result function because it will frees the memory associated with a result object so when while loop run it will not show any result.
$query = "SELECT * FROM user_account WHERE user_id = $user_id ";
$query .= "SELECT * FROM user_profile WHERE user_id = $user_id ";
if (mysqli_multi_query($mysqli, $query)) {
do {
if ($result = mysqli_store_result($mysqli)) {
while ($row = mysqli_fetch_assoc($result)) {
var_dump($row); //for checking result
// Now use array to show your result
}
} }while (mysqli_next_result($mysqli)) ;
You should always free your result with mysqli_free_result(), when
your result object is not needed anymore.
I am creating dynamic query in PHP.
#$id = $_POST[id];
#$field1 = $_POST[field1];
#$field2 = $_POST[field2];
#$field3 = $_POST[field3];
$id = "id";
$field1 = "222";
$field2 = "787";
$field3 = "4444444";
$whereArr = array();
if($id != "") $whereArr[] = "id = {$id}";
if($field1 != "") $whereArr[] = "field1 = {$field1}";
if($field2 != "") $whereArr[] = "field2 = {$field2}";
if($field3 != "") $whereArr[] = "field3 = {$field3}";
$whereStr = implode(" AND ", $whereArr);
$query = "Select * from assignments WHERE {$whereStr}";
echo $query;
It is working fine.
Select * from assignments
WHERE id = id AND field1 = 222 AND field2 = 787 AND field3 = 4444444
I am getting the correct query but mysql is no longer maintained. So, I am using prepared statement like this.
$firstname = 'Patrick';
$lastname = 'Allaert';
$query = 'SELECT * FROM users';
$cond = array();
$params = array();
if (!empty($firstname)) {
$cond[] = "firstname = ?";
$params[] = $firstname;
}
if (!empty($lastname)) {
$cond[] = "lastname = ?";
$params[] = $lastname;
}
if (count($cond)) {
$query .= ' WHERE ' . implode(' AND ', $cond);
}
echo $query;
Problem is how can i bind the parameters.
$stmt->bind_param("sss", $firstname, $lastname, $email);
Thanks for your advise.
You can pass the array into the execute and it will bind the values of that array.
$firstname = 'Patrick';
$lastname = 'Allaert';
$query = 'SELECT * FROM users';
$cond = array();
$params = array();
if (!empty($firstname)) {
$cond[] = "firstname = ?";
$params[] = $firstname;
}
if (!empty($lastname)) {
$cond[] = "lastname = ?";
$params[] = $lastname;
}
if (count($cond)) {
$query .= ' WHERE ' . implode(' AND ', $cond);
}
$stmt = $pdo->prepare($query);
$stmt->execute($params);
You can see this approach on the manual as example #3. http://php.net/manual/en/pdo.prepared-statements.php
Mysqli approach:
$firstname = 'Patrick';
$lastname = 'Allaert';
$query = 'SELECT * FROM users';
$cond = array();
$params = array();
if (!empty($firstname)) {
$cond[] = "firstname = ?";
$params[] = $firstname;
}
if (!empty($lastname)) {
$cond[] = "lastname = ?";
$params[] = $lastname;
}
if (count($cond)) {
$query .= ' WHERE ' . implode(' AND ', $cond);
}
$stmt = $mysqli->prepare($query);
if(!empty($params)) {
$n = count($params);
$a_params[] = & str_repeat('s', $n);
for($i = 0; $i < $n; $i++) {
$a_params[] = & $params[$i];
}
call_user_func_array(array($stmt, 'bind_param'), $a_params);
}
$stmt->execute();
$res = $stmt->get_result();
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
print_r($row);
}
No need for arrays in your script
you can use script like below:
$where = " 1=1";
if($id != "") $where .= " and id = $id ";
if($field1 != "") $where .= " and field1 = '" . $field1 . "' ";
if($field2 != "") $where .= " and field2 = '" . $field2 . "' ";
if($field3 != "") $where .= " and field3 = '" . $field3 . "' ";
$query = "Select * from assignments WHERE $where";
echo $query;
I'm using this query in my php file:
<?php
require_once("database/config.php");
$customerNr = $_POST['customer_nr'];
$customerUuid = '';
$name = '';
$query = "SELECT HEX(uuid) AS customer_uuid, name FROM customers
WHERE customer_number = :customerNr";
$sql = $db->prepare($query);
$sql->bindValue(":customerNr", $customerNr);
$sql->execute();
if ($row = $sql->fetch()) {
$name .= $row["name"];
$customerUuid .= $row["customer_uuid"];
}
When I use echo "$customerNr<br>$name<br>$customerUuid"; I can see all these data.Now I want to use $customerUuid in another query in the same php file but it's not working.
$addressUuid = '';
$street = '';
$zipCode = '';
$city = '';
$query = "SELECT HEX(uuid) AS address_uuid, street, zip_code, city
FROM addresses WHERE customer_uuid = UNHEX(:customerUuid)";
$sql = $db->prepare($query);
$sql->bindValue(":customerUuid", $customerUuid);
$sql->execute();
if ($row = $sql->fetch()) {
$street .= $row["street"];
$zipCode .= $row["zip_code"];
$city .= $row["city"];
$addressUuid .= $row["address_uuid"];
}
Could anybody help me how to prepare this query?
I trying to do all my querys with prepared statements but is new for me and I have some troubles. This is first query and doesn't echo result from table. This is what I've done so far. May be is realy newbie question but is something completely new for me.
if(isset($_GET['joke_id'])){
$joke_id = $_GET['joke_id'];
$qry = $con->prepare("SELECT * FROM joke WHERE joke_cat = ?");
$qry->bind_param('i', $joke_id);
$qry->execute();
$result = $qry->get_result();
$result->fetch_array();
$result = mysqli_query($con, $qry) or die("Query failed: " . mysqli_errno($con));*/
$line = mysqli_fetch_array($result, MYSQL_BOTH);
if (!$line) echo '';
$previd = -1;
$currid = $line[0];
if (isset($_GET['id'])) {
$previous_ids = array();
do {
$previous_ids[] = $line[0];
$currid = $line[0];
if ($currid == $_GET['id']) break;
$previd = end($previous_ids);
$line = mysqli_fetch_array($result, MYSQL_BOTH);
} while ($line);
}
if ($line) {
echo "<div id=\"box\">";
echo nl2br($line['text']) . "<br /><br />";
echo "<div id=\"share\"><span class='st_facebook' displayText='Facebook'></span>
<span class='st_twitter' displayText='Tweet'></span>
<span class='st_googleplus' displayText='Google +'></span></div>";
echo '<br /><br /><br />';
echo "</div>";
}
else echo '<p>Empty category</p><br/>';
This is what I use right now before to try PDO and it's work with no problems.
qry = "SELECT * FROM joke WHERE joke_cat = '$joke_id'";
$result = mysqli_query($con, $qry) or die("Query failed: " . mysqli_errno($con));
$_GET['joke_id'] and $_GET['joke_cat'] is set ?
or try
$qry = $con->prepare("SELECT * FROM joke WHERE joke_cat =:joke_cat");
$qry->bindParam(':joke_cat', $_GET['joke_cat'], PDO::PARAM_STR);
$qry->execute();
$result = $qry->fetchAll();
I'm attempting the modify this Modx Snippet so that it will accept multiple values being returned from the db instead of the default one.
tvTags, by default, was only meant to be set to one variable. I modified it a bit so that it's exploded into a list of variables. I'd like to query the database for each of these variables and return the tags associated with each. However, I'm having difficulty as I'm fairly new to SQL and PHP.
I plugged in $region and it works, but I'm not really sure how to add in more WHERE clauses for the $countries variable.
Thanks for your help!
if (!function_exists('getTags')) {
function getTags($cIDs, $tvTags, $days) {
global $modx, $parent;
$docTags = array ();
$baspath= $modx->config["base_path"] . "manager/includes";
include_once $baspath . "/tmplvars.format.inc.php";
include_once $baspath . "/tmplvars.commands.inc.php";
if ($days > 0) {
$pub_date = mktime() - $days*24*60*60;
} else {
$pub_date = 0;
}
list($region, $countries) = explode(",", $tvTags);
$tb1 = $modx->getFullTableName("site_tmplvar_contentvalues");
$tb2 = $modx->getFullTableName("site_tmplvars");
$tb_content = $modx->getFullTableName("site_content");
$query = "SELECT stv.name,stc.tmplvarid,stc.contentid,stv.type,stv.display,stv.display_params,stc.value";
$query .= " FROM ".$tb1." stc LEFT JOIN ".$tb2." stv ON stv.id=stc.tmplvarid ";
$query .= " LEFT JOIN $tb_content tb_content ON stc.contentid=tb_content.id ";
$query .= " WHERE stv.name='".$region."' AND stc.contentid IN (".implode($cIDs,",").") ";
$query .= " AND tb_content.pub_date >= '$pub_date' ";
$query .= " AND tb_content.published = 1 ";
$query .= " ORDER BY stc.contentid ASC;";
$rs = $modx->db->query($query);
$tot = $modx->db->getRecordCount($rs);
$resourceArray = array();
for($i=0;$i<$tot;$i++) {
$row = #$modx->fetchRow($rs);
$docTags[$row['contentid']]['tags'] = getTVDisplayFormat($row['name'], $row['value'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
}
if ($tot != count($cIDs)) {
$query = "SELECT name,type,display,display_params,default_text";
$query .= " FROM $tb2";
$query .= " WHERE name='".$region."' LIMIT 1";
$rs = $modx->db->query($query);
$row = #$modx->fetchRow($rs);
$defaultOutput = getTVDisplayFormat($row['name'], $row['default_text'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
foreach ($cIDs as $id) {
if (!isset($docTags[$id]['tags'])) {
$docTags[$id]['tags'] = $defaultOutput;
}
}
}
return $docTags;
}
}
You don't add in more WHERE clauses, you use ANDs and ORs in the already existing where clause. I would say after the line $query .= " WHERE stv.name = '".$region... you put in
foreach ($countries as $country)
{
$query .= "OR stv.name = '{$country}', ";
}
but I don't know how you want the query to work.