I am looking to insert a single selection into a field for multiple users. I have the following code, when the selection is made and submit is entered. I do not get an error, I get the next page with the message posted 5 times, which is how many users are not it the weekpicks table. But nothing is inserted into the DB.
<?
// This code is to use to place info into the MySQL
$sTeam1 = $_POST['sTeam1'];
// (WHERE username FROM authorize WHERE username not in ( SELECT username FROM weekpicks WHERE whatweek='$totalnoOfWeek' )" .
//$nMemberID = (integer) Query
$sql_events = mysql_query("SELECT username FROM authorize WHERE username not in ( SELECT username FROM weekpicks WHERE whatweek='$totalnoOfWeek' )") or die(mysql_error());
while ($row = mysql_fetch_array($sql_events)) {
$username = $row["username"];
("INSERT INTO weekpicks SET " . "username = '" . ($username) . "'," . "date_create = NOW(), " . "whatweek = '" . ($totalnoOfWeek) . "'," . "team = '" . addslashes($sTeam1) . "'" . 'INSERT');
echo "<HTML>
<BODY>
<h2>Your pick of " . ($sTeam1) . ", for week " . ($totalnoOfWeek) . ", has been added.</h2>
<P align=left>Return to main page</p>
</BODY>
</HTML>";
}
?>
You are creating the string for insert but you are not running it.
Fixing your code it'd be:
while ($row = mysql_fetch_array($sql_events)) {
$username = $row["username"];
mysql_query("INSERT INTO weekpicks SET " . "username = '" . ($username) . "'," . "date_create = NOW(), " . "whatweek = '" . ($totalnoOfWeek) . "'," . "team = '" . addslashes($sTeam1) . "'");
//echo ...
}
Fixing the string syntax you could do this, which looks nicer. Also using mysql_real_escape_string() instead of addslashes(), since addslashes is not as safe as mysql's native function for php.
$sTeam1 = mysql_real_escape_string($sTeam1);
mysql_query("INSERT INTO weekpicks SET username = '$username', date_create = NOW(), whatweek = '$totalnoOfWeek', team = '$sTeam1');
Another thing I must tell you:
Stop using mysql_*, use mysqli_* instead.
mysql_ was removed from PHP7 and deprecated after PHP 5.5
It's not as safe as mysqli_, so consider improving your code to the new model.
Follow this guide in order to change your code properly.
Related
I am trying to obtain data from the current session and the field "bidder_id" from tbl_bidder where the field "accept" has the value Accepted, but I get data of all the users in that table which is not I want. This is my code
<?php } else if (($_SESSION['Usertype']) == 'recruiter') { ?>
<table class="table table-hover">
<?php
$u_id = $_SESSION['UserID'];
$notifyR = " SELECT bidid, recbid_id, bidder_id, selected, accept FROM tbl_bides WHERE recbid_id = '" . $u_id . "'";
$ResultR = mysql_query($notifyR, $con);
while ($rowR = mysql_fetch_array($ResultR)) {
if ($rowR['accept'] == "Accepted") {
echo "<h3 style='color:#001F7A;'><b>You Have Updates </b><i class='fa fa-bell-o'></i></h3>";
echo $rowR['bidder_id'];
}
$recR = "SELECT users_id, first_name, last_name FROM tbl_users WHERE users_id = '" . $rowR['bidder_id'] . "'";
$recResultB = mysql_query($recR, $con)or die(mysql_error());
while ($rowre = mysql_fetch_array($recResultB)) {
echo " <tr><td>" . $rowre['first_name'] . " " . $rowre['last_name'] . "</td></tr>";
}
}
?>
Please help!!!
Change From
$notifyR = " SELECT bidid, recbid_id, bidder_id, selected, accept FROM tbl_bides WHERE recbid_id = '" . $u_id . "'";
To
$notifyR = " SELECT bidid, recbid_id, bidder_id, selected, accept FROM tbl_bides WHERE recbid_id = '" . $u_id . "' and accept = 'Accepted' ";
add this on your query and accept = 'Accepted' in $notifyR
I hope you might need to use the following query if you stored the user id in $_SESSION['UserID']. May be logical error: And also use mysqli_query instead of mysql_query which is deprecated in latest php versions. And instead of binding the variable directly in query, use bind param of prepared statement.
$recR = "SELECT users_id, first_name, last_name FROM tbl_users WHERE users_id = '" . $_SESSION['UserID'] . "' LIMIT 1";
If you only want to execute the second query (selecting the user associated with the given bid) when the bid has been "accepted" then you need to move that code into your conditional:
if ($rowR['accept'] == "Accepted") {
echo "<h3 style='color:#001F7A;'><b>You Have Updates </b><i class='fa fa-bell-o'></i></h3>";
echo $rowR['bidder_id'];
$recR = "SELECT users_id, first_name, last_name
FROM tbl_users
WHERE users_id = '" . $rowR['bidder_id'] . "'";
$recResultB = mysql_query($recR, $con)or die(mysql_error());
while ($rowre = mysql_fetch_array($recResultB)) {
echo " <tr><td>" . $rowre['first_name'] . " " . $rowre['last_name'] . "</td></tr>";
// echo $rowre['users_id'];
}
}
You may want to consider using a newer interface to MySQL, such as PDO, and protecting your code from SQL injection attacks by using techniques such as prepared statements or at least input cleansing.
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);
}
Please help me to solve this. As I am just in a learning phase of PHP/Mysql.
I have a php feedback form as a rating system from 1-5. You can find my form here http://innovatrix.co.in/feedback_priyajit/feedback%20form1.html
Every time a user provide feedback it saves form values into a mysql database. Below is my database structure.
Now I want to calculate average data of every row (like waiting) and show it on a php file as a graph and also separate graph for every option but on a same page.
I know I can use query SELECT AVG(waiting) FROM feedback to get an average of "waiting"
But how can I do this for every options from a same file and also show it as a graph. Database will be updated frequently, thus it should reflect the graph also.
Please help me with a concept for achieving this.
Below is my php file which I am using to store form values into database.
<title>process</title>
<?php
$host="localhost";
$user_name="pramir_feedback";
$pwd="feedback";
$database_name="pramir_feedback";
$db=mysql_connect($host, $user_name, $pwd);
if (mysql_error() > "") print mysql_error() . "<br>";
mysql_select_db($database_name, $db);
if (mysql_error() > "") print mysql_error() . "<br>";
$waiting = $_POST['radio1'];
$consultation = $_POST['radio2'];
$preoperative = $_POST['radio3'];
$specialists = $_POST['radio4'];
$assistants = $_POST['radio5'];
$painful = $_POST['radio6'];
$operatingroom = $_POST['radio7'];
$thought = $_POST['radio8'];
$recommend = $_POST['radio9'];
$suggestions = $_POST['suggestions'];
$query = "insert into feedback (waiting, consultation, preoperative, specialists, assistants, painful, operatingroom, thought, recommend, suggestions) values ('" . $waiting . "', '" . $consultation . "', '" . $preoperative . "', '" . $specialists . "', '" . $assistants . "', '" . $painful . "', '" . $operatingroom . "', '" . $thought . "', '" . $recommend . "', '" . $suggestions . "')";
if (mysql_error() > "") print mysql_error() . "<br>";
$qresult = mysql_query($query);
echo "<h1>Thank you for submitting your details!</h1>";
?>
If you want all the averages in one query, you can just delimit them with commas.
SELECT AVG(waiting), AVG(consultation), AVG(preoperative), AVG(specialists), ...... FROM feedback
If you want to know how to put them in a graph, take a look at one of the many jQuery graph or plot makers, like: http://www.jqplot.com/tests/bar-charts.php
I have the following code trying to catch up to 15 entries upon submission, however it is only catching the first entry in the database and I am receiving the following error message:
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 '1' at line 1.
<?php
for($i = 0; $i < 15; $i++)
{
$tournament = $_POST['tournament'];
$agegroup = $_POST['agegroup'];
$teamname = $_POST['teamname'];
$coach = $_POST['coach'];
$coachaau = $_POST['coachaau'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$astcoach = $_POST['astcoach'];
$astno = $_POST['astno'];
$astphone = $_POST['astphone'];
$astemail = $_POST['astemail'];
$manager = $_POST['manager'];
$managerno = $_POST['managerno'];
$managerphone = $_POST['managerphone'];
$manageremail = $_POST['manageremail'];
$name = $_POST['name'][$i];
$grade = $_POST['grade'][$i];
$bday = $_POST['bday'][$i];
$aauno = $_POST['aauno'][$i];
if(empty($name) || empty($grade) || empty ($bday) || empty ($aauno))
{
echo ' ';
}
elseif(
$result = mysql_query("INSERT INTO roster (tournament, agegroup, teamname, coach, coachaau, phone, email, astcoach, astno, astphone, astemail, manager, managerno, managerphone, manageremail, name, grade, bday, aauno)
VALUES (
'". mysql_real_escape_string($tournament) . "',
'". mysql_real_escape_string($agegroup) . "',
'". mysql_real_escape_string($teamname) . "',
'". mysql_real_escape_string($coach) . "',
'". mysql_real_escape_string($coachaau) . "',
'". mysql_real_escape_string($phone) . "',
'". mysql_real_escape_string($email) . "',
'". mysql_real_escape_string($astcoach) . "',
'". mysql_real_escape_string($astno) . "',
'". mysql_real_escape_string($astphone) . "',
'". mysql_real_escape_string($astemail) . "',
'". mysql_real_escape_string($manager) . "',
'". mysql_real_escape_string($managerno) . "',
'". mysql_real_escape_string($managerphone) . "',
'". mysql_real_escape_string($manageremail) . "',
'". mysql_real_escape_string($name) . "',
'". mysql_real_escape_string($grade) . "',
'". mysql_real_escape_string($bday) . "',
'". mysql_real_escape_string($aauno) . "');"));
#mysql_query($result)or die(mysql_error());
};
?>
The problem is that you have two mysql_query calls here, and while the first one works on the valid query string, the second - #mysql_query($result) works on its result - i.e., string '1'. But you actually don't need that call, as the first query should have already sent the data to DB.
The quick fix would be checking $result itself (instead of #mysql_query($result)or die(mysql_error()); line):
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Said all that, I'd like to remind you that mysql_query (as whole family of mysql_ functions) is deprecated. If you used PDO or MySQLi, you would be able to use a single prepared statement, filled by new data at each iteration.
Also (kudos to #djot for mentioning that) it's not efficient to extract non-array variables from $_POST again and again, instead of doing it just once - before the loop. This way (if you stay with mysql) you won't have to escape them each time as well. Actually, I'd use something like that here:
$fieldsToInsert = array('tournament', 'agegroup', 'teamname', ...);
$valuesToInsert = [];
foreach ($fieldsToInsert as $field) {
if (! isset($_POST[$field])) {
// actually it's not clear what to do here:
// should we signal an error immediately with, or use some fallback value
}
else {
$valuesToInsert[$field] = mysql_real_escape_string($_POST[$field]);
}
}
This way you'll be able to streamline the code that creates a query as well.
Ok, I am querying my DB for a file. And I want to use a PHP global variable and stick it somewhere in that output using say a '$dir' in my table. Any possible way to do so?
Just use it in a string for the query like you would in any other string. eg:
$sql = "UPDATE TABLE x SET dir=" . $dir . " WHERE id=" . $id;
Though if you do this and your variables use user input it's VERY IMPORTANT to sanitize them against SQL injection and such. The function mysql_real_escape_string() is provided for just such instances.
$sql = "UPDATE TABLE x SET dir=" . mysql_real_escape_string($dir) . " WHERE id=" . mysql_real_escape_string($id);
$query = "SELECT '" . $dir . "' as myVariable, userName, userpassword from users where userName = ...."
The first reply was missing some quotes:
$sql = "UPDATE TABLE x SET dir=" . $dir . " WHERE id=" . $i
->
$sql = "UPDATE TABLE x SET dir='" . mysql_real_escape_string($dir) . "' WHERE id=" . $i
and
$sql = "UPDATE TABLE x SET dir=" . mysql_real_escape_string($dir) . " WHERE id=" . mysql_real_escape_string($id);
->
$sql = "UPDATE TABLE x SET dir='" . mysql_real_escape_string($dir) . "' WHERE id=" . mysql_real_escape_string($id);