So i'm not that experienced in programming, and am working on some php.
My queries (not counting my broken if-else statements >_>), but when I submit 1 query (query2 for example), that works, it prints the results, as well as the results of another query7. How can I stop that?
Also if anyone has any clue where I failed in my if-else statements for the first query and query6, I'd appreciate some insight (they all use html submit buttons)
Thanks!
Here's my problem php code:
$lastName = $_POST['lastName'];
if ($_Post['lastName'] = "") {
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE s.Contact_con_id = c.con_id ";
} Else {
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE s.Contact_con_id = c.con_id
AND con_lname = ";
}
$query = $query . "'" . $lastName . "' ORDER BY con_lname;";
$rgroups = $_POST['rgroups'];
if ($_Post['rgroups'] = "") {
$query6 = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local'
AND r.rev_groups_id = ";
$query6 = $query6 . "'" . $rgroups . "' Group BY r.rev_groups_id;";}
Else {
$query6 = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local'
AND r.rev_groups_id = ";
$query6 = $query6 . "'" . $rgroups . "' ";}
$check = $_POST['check'];
$query7 = "Select c.con_fname, c.con_lname, s.Contact_con_id,
IF(s.Contact_con_id IS NULL, 'NO', 'YES')
From Contact c Left Join (Select Contact_con_id FROM Speakers
WHERE speaker_year = '". $check . "') As s
ON c.con_id = s.Contact_con_id";
$query7 = $query7 . " ORDER BY c.con_fname;";
(this is the code that prints on every result)
$average = $_POST['average'];
$query5 = "SELECT c.con_fname, r.Reviewer_Contact_con_id, question_id, AVG( DISTINCT question_score)
FROM Contact c, Individual_Review r
WHERE r.Reviewer_Contact_con_id = c.con_id
AND con_fname = ";
$query5 = $query5 . "'" . $average . "' GROUP BY r.Proposal_proposal_id;";
(example of working code. you can put in George next to con_fname to get a result)
// 1. Format your code with indents, etc.
// 2. Comment your code
// 3. Don't pass $_POST data straight to your sql.
// 4. Variables are case sensitive, including POST
$lastName = $_POST['lastName'];
if ($lastName = "") {
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE
s.Contact_con_id = c.con_id ";
}else{
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE
s.Contact_con_id = c.con_id
AND con_lname = ";
}
$query = $query . "'" . $lastName . "' ORDER BY con_lname;";
// if you did the first if, then this broke.
// Use:
// echo $query;
// to see what you have so far.
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE
s.Contact_con_id = c.con_id
AND con_lname = '".$lastName."' ORDER BY con_lname";
$rgroups = $_POST['rgroups'];
// you can go like $query .=
// you don't have to do $query = $query;
// so all of this could be:
$query6 = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local' ";
if ($_Post['rgroups'] = "") {
$query6 .= " AND r.rev_groups_id = '" . $rgroups . "' Group BY r.rev_groups_id;";
}else{
$query6 = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local'
AND r.rev_groups_id = '" . $rgroups . "' ";
}
$check = $_POST['check'];
You could add your $query7 in some if condition to avoid that
Note: I am dealing only with your PHP structure. I haven't looked at your SQL syntax at all. But I gave you the tools to see if SQL is returning what you think it should be returning.
<?PHP
// here are some functions for ya
function sqlarr($sql, $numass=MYSQL_BOTH) {
// MYSQL_NUM MYSQL_ASSOC MYSQL_BOTH
$got = array();
$result=mysql_query($sql) or die("$sql: " . mysql_error());
if(mysql_num_rows($result) == 0)
return $got;
mysql_data_seek($result, 0);
while ($row = mysql_fetch_array($result, $numass)) {
array_push($got, $row);
}
return $got;
}
// Sql fetch assoc
function sqlassoc($sql){
$query = mysql_query($sql) or die("$sql:". mysql_error());
$row = mysql_fetch_assoc($query);
return $row;
}
function sqlrow($sql){
$query = mysql_query($sql) or die("$sql:". mysql_error());
$row = mysql_fetch_row($query);
return $row;
}
function sqlquery($sql){
$query = mysql_query($sql) or die("$sql:". mysql_error());
return $row;
}
function printr( array $array, $label = '' ){
echo '<pre>'.$label;
print_r( $array );
echo '</pre>';
}
// This isn't the best, but it's better than nothing
// use PDO when you get more advanced
function makeSomewhatSafe($str){
return htmlspecialchars(stripslashes(strip_tags($str, '<p>')), ENT_QUOTES);
}
// good practice: initiate any variables you use at the beginning
// we're going to go ahead and strip them here too to try to avoid sql injection
$rgroups = makeSomewhatSafe($_POST['rgroups'] );
$lastName = makeSomewhatSafe( $_POST['lastName'] );
$query = NULL;
$speakerContactResulst = array();
$check = makeSomewhatSafe( $_POST['check'] );
$average = makeSomewhatSafe($_POST['average']);
// if($_Post['lastName'] = "") {
// we're going to see if it has a value
// another way to do this if your empty isn't working is to do
// if( strlen( $lastName ) > 0 ){
if( empty( $lastName ) ){
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE s.Contact_con_id = c.con_id ";
}else{
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE s.Contact_con_id = c.con_id
AND con_lname = ";
}
$query .= "'" . $lastName . "' ORDER BY con_lname";
echo 'This query states: '.$query.' <br /><br />';
$speakerContactResulst = sqlarr( $query );
printr( $speakerContactResulst, 'speakerContactResulst ');
if ( ! empty( $rgroups ) ){
$query = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local'
AND r.rev_groups_id = '" . $rgroups . "' Group BY r.rev_groups_id;";
}else{
// I dont know if you matters, but keep your else's more compact. Don't do like you had with the else on a new line
// str'; }
// else {
$query = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local'
AND r.rev_groups_id = '" . $rgroups . "' ";
}
$groupResults = sqlarr( $query );
printr( $groupResults, 'groupResults' );
$query = "Select c.con_fname, c.con_lname, s.Contact_con_id,
IF(s.Contact_con_id IS NULL, 'NO', 'YES')
From Contact c Left Join (Select Contact_con_id FROM Speakers
WHERE speaker_year = '". $check . "') As s
ON c.con_id = s.Contact_con_id ORDER BY c.con_fname;";
$checkResults = sqlarr( $query );
$query = "SELECT c.con_fname, r.Reviewer_Contact_con_id, question_id, AVG( DISTINCT question_score)
FROM Contact c, Individual_Review r
WHERE r.Reviewer_Contact_con_id = c.con_id
AND con_fname = '" . $average . "' GROUP BY r.Proposal_proposal_id;";
$averageResults = sqlarr( $query );
?>
Related
Turning phrases entered in a Form input into an array to pass into a MySQL select statement where clause using MySQLi. The php code I have achieves this, but I can't workout how to parameterise the query to prevent against sql injection attacks. I've had a look at a few questions on this site, but I'm struggling to relate it to my code.
if(!empty($_POST['Message']))
{
$searchStr = get_post($con,'Message');
$aKeyword = explode(" ", $searchStr);
$query ="SELECT m.ID, m.MessageText FROM MessageMain m LEFT OUTER JOIN Likes l on m.ID = l.PostID WHERE MessageText LIKE '%" . $aKeyword[0] . "%'";
for($i = 1; $i < count($aKeyword); $i++) {
if(!empty($aKeyword[$i])) {
$query .= " OR MessageText like '%" . $aKeyword[$i] . "%'";
}
}
$query .= " GROUP BY m.ID, m.MessageText ORDER BY count(m.id) desc";
$result = $con->query($query);
$rowcount=mysqli_num_rows($result);
If you would like to build the WHERE clause dynamically based on the number of keywords to match you could do it like this:
if (!empty($_POST['Message'])) {
$searchStr = get_post($con, 'Message');
$aKeyword = explode(" ", $searchStr);
$whereClauseArr = [];
foreach ($aKeyword as $keyword) {
if ($keyword) {
$whereClauseArr[] = "MessageText LIKE ?";
$whereValues[] = '%'.$keyword.'%';
}
}
$stmt = $con->prepare(
'SELECT m.ID, m.MessageText
FROM MessageMain m
LEFT OUTER JOIN Likes l on m.ID = l.PostID
WHERE '.implode(' OR ', $whereClauseArr).'
GROUP BY m.ID, m.MessageText ORDER BY count(m.id) desc'
);
$stmt->bind_param(str_repeat('s', count($whereValues)), ...$whereValues);
$stmt->execute();
$result = $stmt->get_result();
}
Although in your case, checking the same column against multiple values would probably be better done with regular expression. This would make your query simpler and potentially also faster depending on the number of keywords you have.
if (!empty($_POST['Message'])) {
$searchStr = get_post($con, 'Message');
$aKeyword = explode(" ", $searchStr);
$aKeyword = array_filter($aKeyword); // Remove empty values
$stmt = $con->prepare(
'SELECT m.ID, m.MessageText
FROM MessageMain m
LEFT OUTER JOIN Likes l on m.ID = l.PostID
WHERE MessageText REGEXP ?
GROUP BY m.ID, m.MessageText ORDER BY count(m.id) desc'
);
$regexString = implode('|', $aKeyword);
$stmt->bind_param('s', $regexString);
$stmt->execute();
$result = $stmt->get_result();
}
I am getting this error , Not able to make out what is going wrong , please help.
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ')' at line 1
SELECT GROUP_CONCAT(DISTINCT ud.userid) as id from pr_users_details ud INNER JOIN pr_users u ON ud.userid = u.id WHERE ud.status = '1' AND ()
My function looks like this:
function get_nomination_emailids($functions, $levels, $roles, $locations, $emails)
{
$SQL.="SELECT GROUP_CONCAT(DISTINCT ud.userid) as id from pr_users_details ud INNER JOIN pr_users u ON ud.userid = u.id WHERE ud.status = '1' ";
if(count($functions)>0)
{
$d = implode(",",$functions);
$whereand[] = " u.departmentid IN (".$d.") ";
}
if(count($levels)>0)
{
$d1 = implode(",",$levels);
$whereand[] = " ud.designation_id IN (".$d1.") ";
}
if(count($roles)>0)
{
$d2 = implode(",",$roles);
$whereand[] = " u.userroleid IN (".$d2.") ";
}
if(count($locations)>0)
{
$d3 = implode(",",$locations);
$whereand[] = " u.branchid IN (".$d3.") ";
}
if(count($emails)>0)
{
$d4 = implode(",",$emails);
$whereor[] = " ud.userid IN (".$d4.") ";
}
$whr = array();
if(isset($whereand))
$whr[] = " (".implode(" AND ",$whereand).") ";
if(isset($whereor))
$whr[] = " (".implode(" OR ",$whereor).") ";
if(count($whr > 0))
{
$SQL .= " AND (".implode(" OR ",$whr).") ";
}
$query = $this->db->query($SQL);
$return = $query->result_array();
return $return[0]['id'];
//print_r($return);die;
}
AND() remove in your query try this.
SELECT GROUP_CONCAT(DISTINCT ud.userid) as id from pr_users_details ud INNER JOIN pr_users u ON ud.userid = u.id WHERE ud.status = '1'
I am trying to create a PHP form using MySQL database.
I have created a dropdown list with the names of samples (like Al, Au...) and a textbox for the values.
My problem that the units are in my database sometimes in ppm, sometimes in pph.
How can I set if the values are in pph, use the $value=$_POST["value"]/10000;
if the values are in ppm, use $value=$_POST["value"]?
Any idea?
My code:
<?php
if (isset($_POST["sample"]))
{
$sample = $_POST["sample"];
$unit = mysql_query("SELECT unit FROM analysis where sample='" . $sample . "'");
if ($unit == 'pph')
{
$value = $_POST["value"] / 10000;
$sql = "SELECT
a.sample,
concat (a.modif, (IF (unit='pph',10000*value,value))),
a.method,
a.mkey,
b.name,
b.from,
b.to,
b.type
FROM
anlysis a,
sample b
WHERE
a.mkey=b.mkey AND sample = '$sample' AND value > '$value'";
$result = mysql_query($sql);
}
else
{
$value = $_POST["value"];
$sql = "SELECT
a.sample,
concat ( a.modif, ( IF (unit = 'pph', 10000 * value, value) ) ),
a.method,
a.mkey,
b.name,
b.from,
b.to,
b.type
FROM
anlysis a,
sample b
WHERE
a.mkey = b.mkey AND sample = '$sample' AND value > '$value'";
$result = mysql_query($sql);
}
}
Thank you!
Here's what I'd suggest:
<?php
if (isset($_POST["sample"])) {
$sample = htmlspecialchars(trim($_POST["sample"])); //A little clean-up wont hurt...
$unit = mysql_query("SELECT unit FROM analysis where sample='" . $sample . "'");
if ($unit == 'pph'){
$postVal= htmlspecialchars(trim($_POST["value"]));
$value = $postVal / 10000;
$sql = "SELECT a.sample,
concat (a.modif, (IF (unit='pph',10000*value, value))),
a.method,
a.mkey,
b.name,
b.from,
b.to,
b.type
FROM
analysis AS a
LEFT JOIN sample AS b
ON a.mkey=b.mkey
WHERE
a.sample='" . $sample . "' AND a.value > '" . $value ."'";
$result = mysql_query($sql);
}
else
{
$postVal= htmlspecialchars(trim($_POST["value"]));
$value = $postVal;
$sql = "SELECT
a.sample,
concat ( a.modif, ( IF (unit = 'pph', 10000 * value, value) ) ),
a.method,
a.mkey,
b.name,
b.from,
b.to,
b.type
FROM
analysis AS a
LEFT JOIN sample AS b
ON a.mkey=b.mkey
WHERE
a.mkey = b.mkey AND sample = '" . $sample . "' AND value > '" . $value . "'";
$result = mysql_query($sql);
}
first
$analysis = mysql_fetch_object($query);
then you can access the value
if ($analysis->unit == 'pph')
I've asked this question before, but got no answers, so I'm asking it again but this time, I will be more specific.
I have an online forum which I created from scratch with php and mysql, I've implemented the image uploading part naming the image by the topic id, from the posts table, Now I'm having problems displaying the images by pulling the name and the extension from the image table and attaching it to the topic id to be displayed. Now this is the code snippet for displaying topics (viewtopic.php)
$sql = "
SELECT SQL_CALC_FOUND_ROWS p.id
, p.subject
, p.body
, p.date_posted
, p.date_updated
, u.name as author
, u.id as author_id
, u.signature as sig
, c.count as postcount
, p.forum_id as forum_id
, f.forum_moderator as 'mod'
, p.update_id
, u2.name as updated_by
FROM forum_forum f
JOIN forum_posts p
ON f.id = p.forum_id
JOIN forum_users u
ON u.id = p.author_id
LEFT
JOIN forum_users u2
ON u2.id = p.update_id
LEFT
JOIN forum_postcount c
ON u.id = c.user_id
WHERE $topicid IN (p.topic_id,p.id)
ORDER
BY p.topic_id
, p.date_posted
LIMIT $start,$limit;
";
$result = mysqli_query($sql, $conn)
or die(mysql_error() . "<br>" . $sql);
while ($row = mysqli_fecth_array($result) )
{
echo "<p>($body) . "</p>";
echo $sig;
}
Now after echo ($body) if I run this query;
$sql = "SELECT * FROM images WHERE name = '$name'";
$result = mysqli_query($sql) or die('Could not SELECT image data ' . mysql_error());
while ($therow = mysql_fetch_array($result))
{
$image_name = $therow["name"] ;
$ext = $therow["extension"];
}
?>
<img src="images/<?php echo $image_name.$ext; ?>" >
Help me, how do i get images to be displayed?
Try replace this:
while ($row = mysqli_fecth_array($result) )
{
echo "<p>($body) . "</p>";
echo $sig;
}
to
while ($row = mysqli_fetch_array($result) )
{
echo "<p>($body)" . "</p>";
echo $sig;
}
and this
$sql = "SELECT * FROM images WHERE name = '$name'";
$result = mysqli_query($sql) or die('Could not SELECT image data ' . mysql_error());
while ($therow = mysql_fetch_array($result))
{
$image_name = $therow["name"] ;
$ext = $therow["extension"];
}
?>
to
$sql = "SELECT * FROM images WHERE name = '$name'";
$result = mysqli_query($sql) or die('Could not SELECT image data ' . mysql_error());
while ($therow = mysqli_fetch_array($result))
{
$image_name = $therow["name"];
$ext = $therow["extension"];
}
?>
Can someone help me convert the following code to Yii query? I would liek it to return array of type models with derived column
$sql = 'UPDATE jobs
RIGHT JOIN (
SELECT jobs.JOBNO,
round(details' . $type['type'] . '.' . $type['km'] . ' * sum(PRICE),2) AS JOBSVALUE
FROM jobs
JOIN projects ON jobs.PROJID = projects.PROJID
JOIN biditems ON projects.id = biditems.project_id
JOIN details' . $type['type'] . ' on jobs.JOBNO = details' . $type['type'] . '.JOBNO
WHERE jobs.PROJID = :pid
GROUP BY jobs.JOBNO
) AS temp ON jobs.JOBNO = temp.JOBNO
SET jobs.VALUE = JOBSVALUE';
$command=$connection->createCommand($sql);
$command->bindValue(":pid", $model->PROJID,PDO::PARAM_INT);
$command->execute();
$sql = "UPDATE jobs j
JOIN (
SELECT j.JOBNO, COUNT(l.JOBNO) AS numlis
FROM lineitems l
RIGHT JOIN jobs j ON j.JOBNO = l.JOBNO
WHERE j.PROJID = :pid
GROUP BY j.JOBNO
) t ON j.JOBNO = t.JOBNO
SET `VALUE` = 0, `EARNED` = 0
WHERE PROJID = :pid AND t.numlis = 0;";
$command=$connection->createCommand($sql);
$command->bindValue(":pid", $model->PROJID,PDO::PARAM_INT);
$command->execute();
1st attempt
$sql = "select jobs.JOBNO, round(details".$type['type'].".".$type['km']." * sum(PRICE),2) AS JOBSVALUE
from jobs
join projects on jobs.PROJID = projects.PROJID
join biditems on projects.id = biditems.project_id
join details".$type['type']." on jobs.JOBNO = details".$type['type'].".JOBNO
where jobs.PROJID = :pid
GROUP BY jobs.JOBNO";
$command=$connection->createCommand($sql);
$command->bindValue(":pid",$model->PROJID,PDO::PARAM_INT);
$result = $command->queryAll();
foreach ($result as $value) {
$job = Jobs::model()->findByPk($value['JOBNO']);
$job->VALUE = $value['JOBSVALUE'];
$job->save();
}
$sql = "SELECT j.JOBNO, COUNT(l.JOBNO) AS numlis
FROM lineitems l
RIGHT JOIN jobs j ON j.JOBNO = l.JOBNO
WHERE j.PROJID = :pid
GROUP BY j.JOBNO";
$command=$connection->createCommand($sql);
$command->bindValue(":pid",$model->PROJID,PDO::PARAM_INT);
$result = $command->queryAll();
foreach ($result as $value) {
if($value['numlis'] == 0){
$job = Jobs::model()->findByPk($value['JOBNO']);
$job->VALUE = 0;
$job->EARNED = 0;
$job->save();
}
}
Just literally following their documentation:
$job = Yii:app()->db
->createCommand()
->select(
'jobs.JOBNO, round(details'.$type['type'].'.'.$type['km'].' * sum(PRICE), 2)'
)
->join('projects', 'jobs.PROJID = projects.PROJID')
->join('biditems', 'projects.id = biditems.project_id')
->join('details'.$type['type'], 'jobs.JOBNO = details'.$type['type'].'.JOBNO')
->where('jobs.PROJID=:pid', array(':pid' = $model->PROJID))
->group('jobs.JOBNO')
->queryRow();