what am trying to do here is get data from mysql generated checkboxes. The check boxes data are in array . So for all the check boxes selected I want to use each as a parameter in a query to get more info from another databastablee.
Sample Code Below
if (isset($_POST['submitCourseCode'])) {
//GET ARRAY FROM DATABASE GENERATED CHECKBOXES
$aElective = $_POST['electiveModules'];
foreach($aElective as $snode) {
echo "$snode <br />";
}
//PASSING EACH DATA FROM ARRAY INTO QUERY
$Query = "SELECT ID,title,credits
FROM module
WHERE ID IN('" . implode("', '", $aElective) ."')";
$Result = mysql_query($Query)
or die ("Query failed: " . mysql_error() . " Actual query: " . $Query);
while ($Row = mysql_fetch_array($Result)) {
$id = htmlentities($Row['ID']);
$title = htmlentities($Row['title']);
$credits = $Row['credits'];
echo "<ul>" . $id . " " . $title . " " . $credits . "</ul>";
}
}
var_dump($Query);
var_dump($Result);
var_dump($Row);
Screenshot of my result
Am guessing something is happening with my query probably because of the implode function but everything seems fine in my query.Any suggestions on what am doing wrong?
You need to trim array elements using array_map('trim', $aElective) as:
$Query = "SELECT ID,title,credits
FROM module
WHERE ID IN('" . implode("','", array_map('trim', $aElective)) ."')";
There is a problem with white spaces before your IDs in IN clause.
Try to add a str_replace() call
$Query = "SELECT ID,title,credits
FROM module
WHERE ID IN('" . str_replace(" ", "", implode("', '", $aElective)) ."')";
Related
I am trying to update the store column by adding new item (string) to the end of the column,
But what happens is the new item is added twice at the end of the column, This is the code:
$query = "SELECT * FROM users";
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
$item = 'item_name';
$store = $row['store'];
$newstore = $store . '|' . $item;
echo 'newstore : ' . $newstore . '<br>'; // It looks normal : store|item
$sql = "UPDATE users SET store='" . $newstore . "' WHERE username='" . $row['username'] . "'";
$conn->query($sql);
}
In in the database I find: store|item|item
Rather than reading the entire table and looping through it with PHP, run just a single UPDATE query to concatenate the extra data onto the column.:
$item = 'item_name';
$query = "UPDATE users SET store=concat(store,'|','$item')";
$result = $conn->query($query);
Note: this form is potentially open to SQL injection if you can't trust the value in $item. You'd do better to use a prepared query if that's the case.
I am trying to updata a database table using pq_query in PHP. I have the following code:
$q = "UPDATE tableName SET ('data1 = " . $data1 . "', data2='" . $data2 . "') WHERE user=".$user;
$success = pg_query($q);
if (!$success) {
$errormessage = pg_last_error();
echo "Error " . $errormessage;
}
I am getting the following error message:
ERROR: syntax error at or near "'data1 = '"
LINE 1: UPDATE tableName SET ('data1 = 10', data2= 20'') WHERE user=
Replace your query with this query
$q = "UPDATE tableName SET data1 = '$data1', data2='$data2' WHERE user='$user'";
Explaination: You should pass variable in single quotes('') if your query in double quotes.
You are using a lot of quotes which it is not understood by PostgreSQL, try simply this :
$q = "UPDATE tableName SET data1 = " . $data1 . ", data2=" . $data2 . " WHERE user=".$user;
Remove those single quotes !
I have following code. With a single select query and an update query.It is working fine when i remove the update query. When i run following complete code then nothing happens.
Please help me I want to update table with every cycle of select query. Is there any way to execute following code.
$query = "SELECT * FROM ab_rec WHERE username='$userid'" or die(mysql_error());
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
$t_name=$row['testname'];
$first_url=$row['first_url'];
$thanks_url=$row['thanks_url'];
$start_date=$row['start_date'];
$parse_first_url = parse_url($first_url); //parsing URL of first page for removing main domain name from it.
$parse_thanks_url = parse_url($thanks_url);
$final_first_url = $parse_first_url['path'] ; //Finally parsed URLs are stored into new variables
$final_thanks_url = $parse_thanks_url['path'] ;
$row['unique_visits'] = calculate_visitors($final_first_url, $start_date);
$row['conversions']= calculate_visitors($final_thanks_url, $start_date);
$row['conversion_percent'] = ($conversions/$unique_visits_first)*100;
$query1="UPDATE `ab`.`ab_rec` SET unique_visits=$row['unique_visits'], conversions=$row['conversions'] , conversion_percent=$row['conversion_percent'], WHERE testname=$row['testname'] " or die(mysql_error());
$result2=mysql_query($query1, $connection);
echo "<tr><td>" . $checkbox . "</td><td>" ."<a href='my_test.php?test_name=$t_name'>".$row['testname'] . "</a></td><td>" . $row['date_of_creation'] . "</td><td>" . $row['unique_visits'] . "</td><td>" . $row['conversions'] . "</td><td>" . $row['conversion_percent'] ."%". "</td></tr>"; //$row['index'] the index here is a field name
}
This:
$query1="UPDATE `ab`.`ab_rec` SET unique_visits=$row['unique_visits'],
conversions=$row['conversions'] , conversion_percent=$row['conversion_percent'],
WHERE testname=$row['testname'] " or die(mysql_error());
$result2=mysql_query($query1, $connection);
Should be:
$query1="UPDATE `ab`.`ab_rec` SET unique_visits=$row['unique_visits'],
conversions=$row['conversions'] , conversion_percent=$row['conversion_percent']
WHERE testname='{$row['testname']}'";
echo $query1; //POST THIS RESULT
$result2=mysql_query($query1, $connection) or die(mysql_error());
so I am building a search script and meed to pass on two variables, but first I want to make sure that the SQL QUery is correct so I am hard-coding the variable for now. So my variable is
$comma_separated = "'Alberta','Ontario'";
This is getting passed through to the query, which looks like this:
$sql = "SELECT * FROM persons WHERE 1=1";
if ($firstname)
$sql .= " AND firstname='" . mysqli_real_escape_string($mysqli,$firstname) . "'";
if ($surname)
$sql .= " AND surname='" . mysqli_real_escape_string($mysqli,$surname) . "'";
if ($province)
$sql .= " AND province='" . mysqli_real_escape_string($mysqli,$comma_separated) . "' WHERE province IN ($comma_separated)";
$sql .= " ORDER BY surname";
and then when the query runs, I get this message:
cannot run the query because: 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 'WHERE province IN ('Alberta','Ontario') ORDER BY surname LIMIT 0, 5' at line 1
But to me the query looks right, what am I missing here?
Thanks in advance.
You can't have WHERE in there twice. You also seem to be trying to filter on province values in two different ways. Based on the assumption that $province will always be an array of values (even if only a single value is given), you can try this:
$sql = "SELECT * FROM persons WHERE 1=1";
if (!empty($firstname)) {
$sql .= " AND firstname='" . mysqli_real_escape_string($mysqli,$firstname) . "'";
}
if (!empty($surname)) {
$sql .= " AND surname='" . mysqli_real_escape_string($mysqli,$surname) . "'";
}
if (!empty($province)) {
array_walk($province, function($value, $key_not_used) use ($mysqli) {
return mysqli_real_escape_string($mysqli, $value);
});
$sql .= " AND province IN ('" . implode(',', $province) . "')";
}
$sql .= " ORDER BY surname";
Your SQL contains two WHERE's.
SELECT * FROM persons WHERE 1=1
AND firstname='fn'
AND surname='sn'
AND province='p'
WHERE province IN ($comma_separated)
ORDER BY surname
Change the last bit to:
$sql .= " AND province='" . mysqli_real_escape_string($mysqli,$comma_separated) . "' AND province IN ($comma_separated)";
Which becomes:
AND province='p'
AND province IN ('Alberta','Ontario')
Change the last part to:
if ($province)
$sql .= " AND province IN (" . mysqli_real_escape_string($mysqli,$comma_separated) . ")";
Below is my small code for inserting some info into AthleteID. It doesn't actually insert the information to the table though, any help is appreciated. (sorry for asking twice, but I think my first question isn't addressing whatever issue is holding me up here!)
<?php
require_once('resources/connection.php');
echo 'hello noob' . '<br />';
$query = mysql_query('SELECT LName, MyWebSiteUserID FROM tuser WHERE MyWebSiteUserID = MyWebSiteUserID');
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebSiteUserID"];
$update = "UPDATE `tuser` SET `AthleteID`='$athleteId' WHERE `MyWebSiteUserID` = `MyWebSiteUserID`;";
while($row = mysql_fetch_array($query)){
mysql_query( $update);
}
Where to begin..
1) Your using mysql and not mysqli. mysql is now deprecated but you could be on a PHP 4 system so keep that in mind.
2) You are building the $athleteID before you have found out what LName and SkillshowUserID is.
3) Your using a where of 1 = 1. You dont need this as it will return true for every row.
4) So...
// Execute a query
$results = mysql_query('SELECT LName, MyWebsiteID FROM tuser WHERE SkillshowUserID = SkillshowUserID');
// Loop through the result set
while($row = mysql_fetch_array($query))
{
// Generate the athleteId
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebsiteID"];
// Generate an sql update statement
$update = "UPDATE `tuser` SET `AthleteID`='" . $athleteId . "' " .
" WHERE LName = '" . $row['LName'] . "' " .
" AND MyWebsiteID = '" . $row['MyWebsiteID'] . "';";
// Fire off that bad boy
mysql_query($update);
}