my name's Tony. I am trying to find the way to change this in SQL:
1/ $sql = "select..from..where column_1 = ".$val_1." and column_2 = ".$val_2." and ...and column_n = ".$val_n." ";
------> $sql = "select..from..where [ column,".$val." ] ";
with column run into 1 -> n; $val run into 1 -> n.
2/ Example: If ($val_2 == '') -> $sql = "...where column_1 = ".$val_1." and column_3 = ".$val_3." and ... column_n = ".$val_n." ";
Can i do it ?
Thank you very much.
Make an array and fill it with values which are not empty:
$sql_where_clause = array();
for ($i = 1; $i <= n; $i++)
{
$val_to_test = 'val_' . $i;
if (!empty($$val_to_test))
$sql_where_clause[] = "column_" . $i . " = '" . $$val_to_test . "'";
}
$sql = "select..from..where " . implode(" AND ", $sql_where_clause);
Related
I am trying to do a search query, but not sure how to put everything together. I am having problem with the range filter part.
What i am trying to achieve:
A search form that
1.) If field A,B(not empty) then put in the search query
2.) search through price column with (price lower range, price higher range)
include the results if it matches Field A,B(if it is not empty) and price(if it is in range).
(if search Fields A, B are empty then display all results that exist between range).
Thanks for your time.
The codes that i have now.
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
session_start();
include 'connect.php';
if($_POST)
{
$A = ($_POST['A']);
$B = ($_POST['B']);
$C = ($_POST['C']);
$pricelow = ($_POST['pricelow']);
$pricehigh = ($_POST['pricehigh']);
$sql = array();
if (!empty($A)) {
$sql[] = "A='$A'";
}
if (!empty($B)) {
$sql[] = "B='$B'";
}
if (!empty($C)) {
$sql[] = "C='$C'";
}
if (!empty($price)) {
for($i = pricelow; $i<pricehigh; $i++){
$price = $i;
}
$sql[] = "price='$price'";
$sql = implode(' AND ', $sql);
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . $sql: '');
$result = mysqli_query($con,$sql);
$output = array();
// fetch your results
while( $row = mysqli_fetch_assoc($result) )
{
// add result row to your output's next index
$output[] = $row;
}
// echo the json encoded object
echo json_encode( $output );
}
?>
Edit:
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . $sql: '') . ("AND" 'price' BETWEEN "$pricelow" AND "$pricehigh");
Edit:
if (!empty($pricelow) || !empty($pricehigh)) {
$sql[] = $pricehigh>= 'price' and 'price'>=$pricelow ;
}
$sql = array();
$sql = implode(' AND ', $sql);
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
session_start();
include 'connect.php';
if($_POST)
{
$A = ($_POST['A']);
$B = ($_POST['B']);
$C = ($_POST['C']);
$pricelow = ($_POST['pricelow']);
$pricehigh = ($_POST['pricehigh']);
$query = "SELECT * FROM Listing WHERE ";
$flag = 0;
if (!empty($A)) {
$query .= $flag==0?" A='$A' ":" AND A = '$A'";
$flag = 1;
}
if (!empty($B)) {
$query .= $flag==0?" B = '$B' ":" AND B = '$B'";
$flag = 1;
}
if (!empty($C)) {
$query .= $flag==0?" C='$C' ":" AND C= '$C'";
$flag = 1;
}
if ($flag == 0) {
$query .= " price > $pricelow AND price > $pricehigh"
}
$result = mysqli_query($con,$query);
$output = array();
// fetch your results
while( $row = mysqli_fetch_assoc($result) )
{
// add result row to your output's next index
$output[] = $row;
}
//your rest of the code
>?
I can't test it so, try and report the result!
You are creating an array of conditions and later you try to use that array as a string. This will not work, as the generated query is invalid. Take a look here, implode is a function which implodes an array using a separator. If you use " AND " as separator, then you will get the string you have desired. So, instead of:
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . $sql: '');
do the following:
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');
and your problem should be solved.
EDIT:
I have read your edit and I mean this code in particular:
if (!empty($pricelow) || !empty($pricehigh)) {
$sql[] = $pricehigh>= 'price' and 'price'>=$pricelow ;
}
$sql = array();
$sql = implode(' AND ', $sql);
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');
After you build your array you are initializing it again, thus you lose all information you have processed earlier. Then you implode it twice, which is not needed. Try this way:
if (!empty($pricelow) || !empty($pricehigh)) {
$sql[] = $pricehigh>= 'price' and 'price'>=$pricelow ;
}
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');
I'm new to postresql and i am ashamed to recognize that i am not sure how tot execute correctly an update .
Every time I am trying to pg_query($update); it gives me this : Query failed: ERROR: cannot execute UPDATE in a read-only transaction .
Before this update I have executed a select query .
The select statement retrieves 50000 rows from the database. To be even more specific I am trying to execute a when /case update on 1000 rows. The query is well-formed I have tested it .
$sqlstr = "update abcd set country = CASE" ;
$temp = "";
while($myrow = pg_fetch_assoc($result)) {
if ($cnt < 1000) {
$country = exec('geoiplookup '.$myrow['ip']);
$temp .= " WHEN id = ".$myrow['id']." then '".$country."'";
$cnt++;
}
else {
$sqlstr = $sqlstr.$temp." END ; ";
pg_query($sqlstr);
$temp = "";
}
}
$sqlstr = "update abcd set country = CASE" ;
$temp = "";
while($myrow = pg_fetch_assoc($result))
{
if ($cnt < 1000)
{
$country = exec('geoiplookup '.$myrow['ip']);
$temp .= " WHEN id = ".$myrow['id']." then '".$country."'";
$cnt++;
}
else
{
$sqlstr = $sqlstr.$temp." END ; ";
pg_query($sqlstr);
$temp = "";
}
}
I'm not sure why this SQL query is not working.
I'm new to SQL/PHP so please forgive.
mysql_query("
SELECT * FROM table WHERE name = " . "'Bob'" .
while($i < $size)
{
$i++;
echo "OR name = '";
echo $array[$i] . "'";
} .
" ORDER BY id DESC "
);
Dreamweaver gives me an error saying it is not correct but does not tell me what is wrong.
Is it possible to put a while loop into an sql command?
you can not use a while in a string
$where = "";
if ($size > 0)
{
$where .= " WHERE ";
}
while($i < $size)
{
$i++;
$where .= "OR name = '".$array[$i]."' ";
}
$query = "SELECT * FROM table WHERE name = '".Bob."'".$where." ORDER BY id DESC";
mysql_query($query);
(this code is not tested)
Woot !
You just can't write this :D
Build your OR condition before writing the query and it will be just fine:
$myCondition = " ";
while($i < $size) {
$i++;
$myCondition .= "OR name = '" . $array[$i] . "'";
}
mysql_query(
"SELECT * FROM table WHERE name = " . "'Bob'" . $myCondition . " ORDER BY id DESC ");
echo is to output the string, and it won't return the string.
Something like $str = "aaa" . echo "bbb"; won't work.
For you case, use IN will be better.
foreach ($array as &$name) {
$name = "'".mysql_real_escape_string($name)."'";
}
mysql_query("SELECT * FROM table WHERE name IN (".implode(',', $array).")");
Or use
"SELECT * FROM table WHERE name IN(".implode( ',', $array).")";
Hi I'm really new to php/mysql.
I'm working on a php/mysql school project with 39 fields all in all in a single table.
I want to shorten my codes especially on doing sql queries.
$sql = "INSERT into mytable ('field_1',...'field_39') Values('{$_POST['textfield_1']}',...'{$_POST['textfield_39']}')";
I don't know how to figure out this but , i want something like:
$sql = "Insert into mytable ("----all fields generated via loop/array----") Values("----all form elements genrated via loop/array---")";
Thank you in advance.
<?php
function mysql_insert($table, $inserts) {
$values = array_map('mysql_real_escape_string', array_values($inserts));
$keys = array_keys($inserts);
return mysql_query('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
}
?>
For example:
<?php`enter code here`
mysql_insert('cars', array(
'make' => 'Aston Martin',
'model' => 'DB9',
'year' => '2009',
));
?>
try this it i thhink it il work
You could use implode:
$sql = "
INSERT into mytable
('" . implode("', '", array_keys($_POST) . "')
VALUES
('" . implode("', '", $_POST . "')";
(This assumes the indices of the POST array are also the names of the db table fields)
However, this is extremely insecure since you would directly insert post data into the database.
So the least you should do beforehand is escape the values and make sure they are ok/valid table fields:
// Apply mysql_real_escape_string to every POST value
array_walk($_POST, "mysql_real_escape_string");
and
// Filter out all POST values with invalid indices
$allowed_fields = array('field_1', 'field_2', /* ... */ );
$_POST = array_intersect_key($_POST, $allowed_fields);
<?php
$sql = "Insert into mytable (";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "field_$i";
} else {
$sql .= "field_$i,";
}
}
$sql .= "Values(";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "'" . $_POST[textfield_$i] . "'";
} else {
$sql .= "'" . $_POST[textfield_$i] . "',";
}
}
?>
< ?php
$sql = "Insert into mytable (";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "field_$i";
} else {
$sql .= "field_$i,";
}
}
$sql .= "Values(";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
if(is_int($POST[textfield$i])){
$sql .= $POST[textfield$i];
}
else{
$sql .= "'" . $POST[textfield$i] . "'";
}
} else {
if(is_int($_POST[textfield_$i])){
$sql .= $_POST[textfield_$i] .",";
}
else{
$sql .= "'" . $_POST[textfield_$i] . "',";
}
}
}
?>
it will work for numeric values. you can insert numeric values in single quotes but some times it will create some problems
I have this Function:
function getLow() {
global $db_prefix, $min;
//get latest week with all entered scores
$lastCompletedWeek = getLastCompletedWeek();
$sql = "select u.userID, u.teamName ";
$sql .= "from " . $db_prefix . "users u ";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
for($i = 1; $i <= $lastCompletedWeek; $i++) {
$userScore = getLowScore($i, $result['userID']);
$win[][week] = $i;
$win[][user] = $result['userID'];
$win[][teamName] = $result['teamName'];
$win[][score] = $userScore;
}
$count = count($win);
$lowest = 0;
$min[score] = PHP_INT_MAX;
$min[user] = $result['userID'];
$min[teamName] = $result['teamName'];
for($i = 0; $i < $count; $i++) {
if($win[$i + 1]['user'] == $result['userID']) {
if($win[$i + 3]['score'] < $min[score]) {
$min[score] = $win[$i + 3]['score'];
$lowest = $i;
}
}
}
unset($win[$lowest]);
unset($win[$lowest + 1]);
unset($win[$lowest + 2]);
unset($win[$lowest + 3]);
$win = array_values($win);
//print_r ($min);
//echo $min[teamName] . ' ' . $min[score] . ' ';
}
}
when I call it from another .php file like this:
getLow($min);
I only get the last record....why?
Here is the getLowScores functio as well.
function getLowScore($week, $userID) {
global $db_prefix, $user;
$score = 0;
//get array of games
$games = array();
$sql = "select * from " . $db_prefix . "schedule where weekNum = " . $week . " order by gameTimeEastern, gameID";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
$games[$result['gameID']]['gameID'] = $result['gameID'];
$games[$result['gameID']]['homeID'] = $result['homeID'];
$games[$result['gameID']]['visitorID'] = $result['visitorID'];
$games[$result['gameID']]['tie'] = 1;
if (($result['homeScore'] + (($result['visitorSpread'] * -1))) > ($result['visitorScore'] + (($result['homeSpread'] * -1)))) {
$games[$result['gameID']]['winnerID'] = $result['homeID'];
}
if (($result['visitorScore'] + (($result['homeSpread'] * -1))) > ($result['homeScore'] + (($result['visitorSpread'] * -1)))) {
$games[$result['gameID']]['winnerID'] = $result['visitorID'];
}
if (($result['visitorScore'] + ($result['homeSpread'] * -1)) == ($result['homeScore'] + ($result['visitorSpread'] * -1))) {
$games[$result['gameID']]['winnerID'] = $result['tie'];
}
}
//loop through player picks & calculate score
$sql = "select p.userID, p.gameID, p.pickID, p.points, u.paid ";
$sql .= "from " . $db_prefix . "picks p ";
$sql .= "inner join " . $db_prefix . "users u on p.userID = u.userID ";
$sql .= "inner join " . $db_prefix . "schedule s on p.gameID = s.gameID ";
$sql .= "where s.weekNum = " . $week . " and u.userID = " . $userID . " ";
$sql .= "order by u.lastname, u.firstname, s.gameTimeEastern";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
if (!empty($games[$result['gameID']]['winnerID']) && $result['pickID'] == $games[$result['gameID']]['winnerID']) {
//player has picked the winning team
$score++;
}
if ($result['tie'] == $games[$result['gameID']]['winnerID']) {
//player has picked the winning team
$score++;
}
}
return $score;
}
Thanks in advance for helping!! This is driving me crazy?
Maybe not the answer, but this code is very broken:
$win[][week] = $i;
$win[][user] = $result['userID'];
$win[][teamName] = $result['teamName'];
$win[][score] = $userScore;
First, that adds four new rows to $win, a new one every time you use the [], which I very much doubt is your intent.
Second, those should be quoted, so it is ["week"], not [week]. Turn on PHP warnings and follow them.
I think you want:
$win[] = array(
"week" => $i,
"user" => $result['userID'],
"teamName" => $result['teamName'],
"score" => $userScore,
);
You can make warnings appear with:
error_reporting(E_ALL);
ini_set("display_errors",1);