I'm getting error "Undeclared variable: $start" while using the SQL query below.
<?php
if($Spage == ""){
$Spage = "1";
}
$Sper_page = "5";
$start = ($Spage-1)*$Sper_page;
$sResults = $oCon->dbFetchSmarty("SELECT * FROM experts WHERE exp_process LIKE '%".$process."%' AND exp_machinaries like '%".$machineCat."%' AND exp_country = '". $country."' 'LIMIT $start, $Sper_page'");
?>
You have messed your single quotes. Should be
$sResults = $oCon->dbFetchSmarty("SELECT * FROM experts WHERE exp_process LIKE '%".$process."%' AND exp_machinaries like '%".$machineCat."%' AND exp_country = '". $country."' LIMIT $start, $Sper_page");
And cleaning up the query a bit:
$sResults = $oCon->dbFetchSmarty("SELECT * FROM experts WHERE exp_process LIKE '%$process%' AND exp_machinaries like '%$machineCat%' AND exp_country = '$country' LIMIT $start, $Sper_page");
Next step to remove would be to use prepared statements and bind these parameters in
Try this: (another way in setting Limit and Offset)
<?php
if($Spage == ""){
$Spage = "1";
}
$Sper_page = "5";
$start = ($Spage-1)*$Sper_page;
$sResults = $oCon->dbFetchSmarty("SELECT * FROM experts WHERE exp_process LIKE '%".$process."%' AND exp_machinaries like '%".$machineCat."%' AND exp_country = '". $country."'LIMIT $per_page OFFSET $start'");
?>
And BTW you misplaced a single quote near LIMIT.
You are making the creation of your query much too complicated and therefore missing some simple errors. Remember that when you use double quoutes " in PHP it will expand $variables into the string for you.
So a simpler and easier to read and therefore debug method would be this
$sql = "SELECT * FROM experts
WHERE exp_process LIKE '%$process%'
AND exp_machinaries like '%$machineCat%'
AND exp_country = '$country'
LIMIT $start, $Sper_page";
$sResults = $oCon->dbFetchSmarty($sql);
You left out a space between LIMIT and '.
It must've been
$country."' ' LIMIT . ........
For best solution to check query is in phpmyadmin. You just echo query and copy/past query section into phpmyadmin. so it will give a proper guidance for your structure of query or any error for same.
Related
I have a web application and I'm trying to modify one of the queries. The query fetches information (from a table named voyage_list) and returns various fields.
I want to modify the query so that it is based on certain filters the user applies (which will be placed in the URL).
I can't get the query to work in the web application, but if I copy the query and execute it directly within PHPMyAdmin, it works fine.
$vesselFilter = $_GET['vesselFilter'];
$vesselArray = explode(',', $vesselFilter);
$arrayCount = count($vesselArray);
$sqlExtend = ' status = 1 AND';
foreach ($vesselArray as $value) {
$i = $i + 1;
$sqlExtend .= " vesselID = '$value'";
if ($i < $arrayCount){
$sqlExtend .= " OR";
}
}
$newQuery = "SELECT * FROM voyage_list WHERE" . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
I appreciate the above is pretty messy, but it's just so I can try and figure out how to get the query to work.
Any help would be greatly appreciated!
Thanks
That query probably doesn't return what you think it does. AND takes precedence over OR, so it will return the first vessel in the list if the status is 1, and also any other vessel in the list, regardless of status.
You'd do better to create a query with an IN clause like this:
SELECT * FROM voyage_list WHERE status = 1 AND vesselID IN(8,9,10)
Here's some code to do just that:
$vesselFilter = $_GET['vesselFilter'];
// Validate data. Since we're expecting a string containing only integers and commas, reject anything else
// This throws out bad data and also protects against SQL injection.
if (preg_match('/[^0-9,]/', $vesselFilter)) {
echo "Bad data in input";
exit;
}
// filter out any empty entries.
$vesselArray = array_filter(explode(',', $vesselFilter));
// Now create the WHERE clause using IN
$sqlExtend = 'status = 1 AND vesselID IN ('.join(',', $vesselArray).')';
$newQuery = "SELECT * FROM voyage_list WHERE " . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
var_dump($query);
I am working on a PHP file and getting via POST this string:
$temas = $_POST['temas']; //$temas = ".45.12.34"
Where each of the numbers should be the id for a table record.
And I have following query
$query = "SELECT * FROM tb_preguntas WHERE tema = '".$temas."'";
I need to put in the WHERE part of the query each of the received id
Something like that: ... WHERE tema = 45 OR tema = 12 OR tema = 34
Of course, on each execution the string changes.
I have tried using the PHP explode function, but I don't know how to implement the result in the query.
My answer won't differ too much from everyone else's but it is an answer to address SQL injection + a solution
$temas = implode(',', explode('.', $_POST['temas']));
$temas = trim($temas);
$res = $conn->prepare('select * from `tb_preguntas` WHERE `tema` in (:temas)');
$res->execute(array(':temas' => $temas));
here we use a prepared statement, now you're code is safe woop woop
As suggested above you can use the IN() function of mysql, however you have to remove the first period '.' and change the rest to commas ','.
$query = "SELECT * FROM `tb_preguntas` WHERE `tema` IN('".str_replace('.',',',trim($temas,'.'))."') ";
best case scenario
$temas = implode(',', explode( '.', $_POST['temas']));
$query = "select * from tb_preguntas WHERE tema in (" . $temas . ")";
but your case, . comes first that makes life so much harder, so a better solution would be
$temas1 = explode( '.', $_POST['temas'] );
$temas2 = array();
foreach( $temas1 as $value ) {
if( is_numeric( $value )) $temas2[] = $value;
}
$query = "select * from tb_preguntas WHERE tema in (" . implode( ',' , $temas2 ) . ")";
Use explode() to split those numbers by .And it must turn into array.
Then run your queries into a loop using the lenth of the array like this:
$id = explode('.',$temas);
foreach($id as $temas_id) {
$query = "SELECT * FROM tb_preguntas WHERE tema = '".$temas_id."'";
if(isset($conn->query(query ))) {
// Execute code here if there's a result.
}
}
Please try this code.
$temas = $_POST['temas'];
$temas = explode('.',$temas);
$query = mysql_query("SELECT * FROM test_stipe WHERE tema in '".implode("', '", $temas)."'");
This code is working fine.
Hi still a beginner in php programming and one of the function of my project is to check if the schedule exist or not in the database. anyway my problem is that the way i created the string query, i am not sure if the string is correct in terms of syntax but the query is correct and tested in the phpmyadmin MySQL GUI.
$start_time = $_POST['Time-In'];
$end_time = $_POST['Time-Out'];
$procedure_date = $_POST['txbDateofProcedure'];
$DateStartTime = $procedure_date." ".$start_time;
$DateEndTime = $procedure_date." ".$end_time;
//Not sure but i think that the $Check-Schedule php syntax is incorrect
$Check_Schedule = "select * from appointment_dim where dentist_id = '$dentist_id'".
"and (CONCAT(appoint_date, ,appoint_timein) between '$DateStartTime' and '$DateEndTime')".
"OR (CONCAT(appoint_date, ,appoint_timeout) between '$DateStartTime' and '$DateEndTime')";
$result_schedule = mysql_query($Check_Schedule,$con);
if(!$result_schedule)
{
trigger_error("Cannot located database".mysql_error());
die();
}
if(mysql_num_rows($result_schedule) > 0)
{
$SchedErrMesg = "The time you requested is already take try again.";
echo"<script type='text/javascript'>alert('$SchedErrMesg');</script>";
die();
}
if you want the delimiter between appoint_date and appoint_time* to be space, you should do this:
CONCAT(appoint_date, ' ', appoint_timein)
but not this:
CONCAT(appoint_date, , appoint_timein)
Also i believe u want the logic like
"dentist_id = x AND (timeBetween1 OR timeBetween2)"
But not that u wrote:
"(dentist_id = x AND timeBetween1) OR timeBetween2"
So try this:
$Check_Schedule = "
SELECT * FROM appointment_dim
WHERE
dentist_id = '$dentist_id'
AND (
(CONCAT(appoint_date, ' ', appoint_timein) BETWEEN '$DateStartTime' AND '$DateEndTime')
OR (CONCAT(appoint_date, ' ', appoint_timeout) BETWEEN '$DateStartTime' AND '$DateEndTime')
)
";
why i can't use this code ? and could anyone tell me what is the correct code ?
$lfr_prfid = "profile='$log_id'";
$lfrsql = "SELECT * FROM friends WHERE user2='$log_id' AND accepted='1'";
$lfrquery = mysqli_query($db_conx, $lfrsql);
while ($lfrrow = mysqli_fetch_array($lfrquery, MYSQLI_ASSOC)) {
$lfr_id = $lfrrow["id"];
$lfr_user1 = $lfrrow["user1"];
$lfr_user2 = $lfrrow["user2"];
$lfr_prfid += " OR profile='".$lfr_user1."'";
}
the last line i wrote this ( += ) and the code doesn't work so how can i do this in another way ? so i can use this in a SELECT statement .
$psql = "SELECT * FROM posts WHERE ".$lfr_prfid." ORDER BY postdate DESC LIMIT 0,20";
$pquery = mysqli_query($db_conx, $psql);
$lfr_prfid.=
Concatenate with . not with +. The + is concatenation in javascript.
so, in php: $myVar.= 'foo';
and in javascript: myVar+= 'foo';
Update based on your edit:
Please, DO NOT use that in a database query. Use prepared statements or your code is dangerous.
Change your code to:
$lfr_prfid .= " OR profile='".$lfr_user1."'";
Concatenation in PHP is done with ., not with += as you have written.
Hope this helps!
apologize firstly for my questionable coding in php/mysql however this is all self taught (possibly not best practice)
All my code seems to work , however when the results are written to the page any $dxcall that is not in the $qrzdata database gets filled with the last result all other data displays fine. I have tried changing the like $dxcall to = $dxcall. I have also tried combining the fetch arrays too incase my issues was there too. But clearly my code does not know how to handle where there is not data match in the qrzdata database and to move on.
$frqry is the main data, all the other mysql_query's be it the $squares and $qrzdata are matching what comes from $frqry. Hope this makes sense !!
Here is my code
$frqry = mysql_query("select * from spots where freq between '69900' and '70300' ORDER BY datetime desc limit 30");
While ($r0 = mysql_fetch_array($frqry))
{
$freq = $r0["freq"];
$dxcall = $r0["dxcall"];
$datetime = $r0["datetime"];
$comments = $r0["comments"];
$spotter = $r0["spotter"];
$dt = date('d-m-y H:i ', $datetime);
$qra = $r0["loc"];
$squares = mysql_query("select * from squares where callsign like '$dxcall' limit 1");
while ($r1 = mysql_fetch_array($squares))
{
$qra = $r1["loc"];
}
$qrzdata = mysql_query("select * from qrzdata where callsign = '".$dxcall."' limit 1");
While ($r2 = mysql_fetch_array($qrzdata))
{
$country = $r2["country"];
$firstname = $r2["firstname"];
$city = $r2["city"];
}
Any help is greatly appreciated. Thank you.
You need to learn about the power of the JOIN ;)
Your whole code could be rewritten in one single query :
disclaimer: not tested, but you certainly get the idea
SELECT * FROM spots
JOIN squares ON (squares.callsign = spots.dxcall) -- this comes in stead of your first inner loop
JOIN qrzdata ON (qrzdata.callsign = spots.dxcall) -- this is your second loop
WHERE freq BETWEEN 69900 AND 70300 -- remove quotes, you are dealing with integers, not strings (hopefully)
You have to reset your vars!
While ($r0 = mysql_fetch_array($frqry))
{
$qra = '';
$country = '';
$firstname = '';
$city = '';
or you will allways get the last value