I have different paramter of particular mysql query I am running so I need to run them in bunch.. so say
$server = 'server_';
for ($a=0 ; $a<5 ; ++$a) {
$criteria = $server . $a;
$query1 = 'select blabh blah not important ' . $criteria . 'order by date desc limit 10';
$query_result = mysql_query($query1);
}
Above only comes back results for server_4
I naively thought I could just do
$query_result .= mysql_query($query1);
But clearly that doesn't work. I hope no one says why don't you run mysql as
like '$server%'
I am looking for to see if what I am trying to do is possible. appending.. I guess string append is possible but I perahps simply don't understand what's coming back from mysql?
fetch code sample
select * from tableName where server like $criteria order by date desc limit 10
=========================================================
code sample
$data = array();
$dataMaster = array();
for ( $x = 0; $x <= 8; $x++ ) {
$server = ‘server_’ . $x;
$myquery = 'select * from serverTable where servername like ' . '"' . $server . '"' . ' order by date1 desc limit 100';
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
for ( $x = 0; $x < mysql_num_rows($query); $x++ ) {
$data[] = mysql_fetch_assoc($query);
}
$data = array_reverse($data);
array_push($dataMaster, $data);
}
echo json_encode($dataMaster)
Try to avoid SQL inside PHP loop, you can do the following instead:
SELECT * FROM serverTable WHERE servername IN
('server_0', 'server_1', 'server_2', 'server_3', 'server_4')
Related
the following sql query works perfectly in phpAdmin.
SELECT response_text FROM statement_responses WHERE response_code = "s1_r1"
it doesn't work without the speech marks around response_code value.
I'm attempting to use the value of response_text in php.
for ($x = 1; $x <= 9; $x++) {
$user_response = ${"statement_" . $x . "_response"};
$sql = "SELECT response_text FROM statement_responses WHERE response_code = \"$user_response\"";
$result = mysqli_query($sql);
$value = mysqli_fetch_object($result);
echo $user_response . "<br>";
echo $sql . "<br>";
echo $result . "<br>";
echo $value . "<br>";
}
The echoes allow me to see what each of the variables contains.
I get the following:
s1_r3 (the value of $user_response)
SELECT response_text FROM statement_responses WHERE response_code = "s1_r3" (the value of $sql - which is identical to the phpAdmin query that works.)
There are no values echoed for $result or $value.
What am I doing wrong, please? Why am I not getting the values from the database into my php code?
The first parameter for the mysqli_query should be the database connection created with mysqli_connect. Similarily, the first parameter for the mysqli_fetch_object, should be the result set identifier returned by mysqli_query.
It is a good practice to check the return values from the functions you call.
firstly, thank you for all of the responses. The following code works - i.e. it returns the value contained in 'response_text' column with the selected row identified by 'response_code' for use as the value of $response_text.
for ($x = 1; $x <= 9; $x++) {
$user_response_pre = ${"statement_" . $x . "_response"};
$user_response = "\"'" . $user_response_pre . "'\"";
$sql = "SELECT response_text FROM statement_responses WHERE response_code = $user_response";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$response_text = $row[0];
${"statement_" . $x . "_complete"} .= $response_text;
}
you can write like this
for ($x = 1; $x <= 9; $x++) {
$user_response = ${"statement_" . $x . "_response"};
$sql = 'SELECT response_text FROM statement_responses WHERE response_code = "'.$user_response.'"';
$result = mysqli_query($sql);
$value = mysqli_fetch_object($result);
echo $user_response . "<br>";
echo $sql . "<br>";
echo $result . "<br>";
echo $value . "<br>";
}
I want to create sql queries dynamically depending upon the data I receive from the user.
Code:
$test = $_POST['clientData']; //It can be an array of values
count($test); //This can be 2 or 3 or any number depending upon the user input at the client
$query = "select * from testTable where testData = ".$test[0]." and testData = ".$test[1]." and . . .[This would vary depending upon the user input]"
Is it possible to achieve the above scenario. I am relatively new in this area.Your guidance would be helpful.
Use:
<?php
$test=$_POST['clientData'];//It can be an array of values
$query = "select *from testtable where 1 ";
foreach($test as $value) {
$query .= " AND testData='" . $value . "'";
}
echo $query;
?>
Use prepared statements:
$query = $dbh->prepare("SELECT * FROM testtable WHERE testData=:test0 and testData=:test1");
$query ->bindParam(':test0', $test0);
$query ->bindParam(':test1', $test0);
$test0 = $test[0];
$test1 = $test[1];
$query->execute();
Rishi that's a very long chapter.
If you want to search into a single field then you can try to do:
<?php
$test = $_POST[ 'clientData' ];
if( is_array( $test ) ){
$select = implode( ",", $test );
} else {
$select = $test;
}
$query=select *from testtable where testData IN ( $select );
?>
This is valid only for searches into a specific field.
If you want to create searches on multiple fields then you need to do a lot of more work, having an associative mapping which can create a relation variable name -> field_to_search
$data = $_POST['data'];
$query = "SELECT";
if ( is_set($data['columns']) )
$query .= " ".implode(',',$data['columns']);
else
$query .= "*";
if ( is_set($data['table']) )
$query .= " ".$data['table'];
and ...
This is very much pseudo code as I don't really know PHP, but could you not do something like this
$query = "select * from testable";
$count = count($test);
if($count > 0)
{
$query .= " where ";
for ($x=0; $x<=$count; $x++)
{
if($x > 0)
{
$query .= " and ";
}
$query .= " testData='" . $test[x] . "'";
}
}
$test=$_POST['clientData'];
$query="select * from testtable where testData='".$test[0]."' and testData='".$test[1]."' and . . .[This would vary depending upon the user input]";
$result = mysql_query($query);
$test=$_POST['clientData'];//It can be an array of values
$dValuesCount = count($test);//This can be 2 or 3 or any number depending upon the user input at the client
$query="select *from testtable ";
if ($dValuesCount > 0 ){
$query .= " WHERE ";
for ($dCounter = 0; $dCounter <= $dValuesCount ; $dCounter++){
$query .= "testData=" . $test[$dCounter];
if ($dCounter != ($dValuesCount - 1)){
$query .= " AND ";
}
}
}
$q="select *from table where ";
$a=count($test)-1;
$b=0;
while($element = current($test)) {
$key=key($array);
if($b!=$a){
$q.=$key."=".$test[$key]." and ";
}
else {
$q.=$key."=".$test[$key];
}
next($array);
$b=$b+1;
}
for this your array must contain columnname as key
for example
$test['name'],$test['lastname']
then it will return
$q="select * from table where name=testnamevalue and lastname=testlastnamevalue";
hope it works
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).")";
I tried combining as suggested in a previous link but Im still getting a error. I am fairly new to php so that is why i have two querys.
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/vhockey/public_html/vhatest/connect.php on line 88
The table is "season12" and the table is "p"
Here is my connect.php file except server info...
function index_team_stats($subconference) {
$return = array();
$query = "SELECT id, teamname, teamnameseason, teamabr
FROM teams
WHERE subconference = '" . $subconference . "'
ORDER BY teamnameseason";
$teams = result_array($query);
foreach ($teams as $team)
{
$query = "SELECT gp, w, l, ol, p
FROM season12
WHERE team = '" . $team['teamnameseason'] . "'
ORDER BY p DESC
LIMIT 0,20'; ";
$results = result_array($query);
if ($results)
{
$results[0]['team'] = str_replace($team['teamnameseason'], '', $team['teamname']);
$results[0]['teamabr'] = $team['teamabr'];
$results[0]['teamid'] = $team['id'];
$return[] = $results[0];
}
}
return $return;
}
function get_team_name($teamnameseason) {
$query = "SELECT teamname FROM teams WHERE teamnameseason = '" . $teamnameseason . "'";
$row = mysql_fetch_row(mysql_query($query));
return str_replace($teamnameseason, '', $row[0]);
}
function result_array($query) {
$results = mysql_query($query) or die("error on: " . $query . " saying: " . mysql_error());
$return = array();
while ($row = mysql_fetch_assoc($results)) {
$return[] = $row;
}
return $return;
}
Here is an image of the info ![All info sorted by team PTS from highest to lowest
Should show Penguins, FLyers, Islanders, Rangers, Devils..
Use a JOIN. An example is below. You may need to tweak based on your specific needs.
SELECT teams.id, teams.teamname, teams.teamnameseason, teams.teamabr, season12.gp,
season12.w, season12.l, season12.ol, season12.p
FROM teams, season12
INNER JOIN season12
ON teams.teamname=season12.team
WHERE teams.subconference = '$subconference'
ORDER BY season12.p
LIMIT 0,20
Please note this code is not tested and may require modification.
You can use php sort function http://php.net/usort
$callback = new function ($el1, $el2) {
if ($el1['points'] == $el2['points']) {
return 0;
}
return ($el1['points'] < $el2['points']) ? -1 : 1;
}
$sorted_result = usort($results, $callback);
I try to load about 30.000 record to mysql select. than i get this warning.
and than i try to break them into smaller limit. Every 1000. but why i still get this warning?
this is my code :
function processDataDb()
{
$rowIncrement = 1000;
$query = "SELECT count( * ) as totalfield FROM `isc_xml_data` ";
$result = mysql_query($query) or die ("$query" . mysql_error());
if ($result)
{
$row = mysql_fetch_assoc($result);
$total_row = $row['totalfield'];
for($i = 0; $i < $total_row ; $i+=$rowIncrement)
{
$sql_c = "SELECT * FROM isc_xml_data order by id LIMIT " . $i . " , " . ($i + $rowIncrement - 1);
$res_c = mysql_query($sql_c) or die (mysql_error());
while($row = mysql_fetch_object($res_c))
{
echo $row->id."\n";
$this->insertAndUpdateProduct($row->xmldata);
}
unset($res_c);
}
} else {
echo "result is unavailable";
}
}
Thanks for any help.
$sql_c = "SELECT * FROM isc_xml_data order by id LIMIT " .
$i . " , " . ($i + $rowIncrement - 1);
http://dev.mysql.com/doc/refman/5.0/en/select.html#id714605
The second argument to LIMIT is how many you want, not the upper bound; try just $rowIncrement.
unset($res_c); It's not valid, there is mysql_free_result($res_c) function for this.
Also, you can do it without first query with count(*) - just make your cycle queries until at least one row returned.
Because of this line:
$this->insertAndUpdateProduct($row->xmldata);
it's your XML processing being very inefficient memory-wise,
while mysql consumes no more than only one row contents.