This is my code for the update:
$key = $skills[$ind];
echo "\t\t<td>" . $key . "</td>\n";
//explode using a comma as a delimiter
$data_n = explode(",", $word);
$score[$key][”Rank”] = $data_n[0];
$score[$key][”Level”] = $data_n[1];
$score[$key][”Exp”] = $data_n[2];
echo "\t\t<td>" .$data_n[0] . "</td>\n";
echo "\t\t<td>" .$data_n[1] . "</td>\n";
echo "\t\t<td>" .$data_n[2] . "</td>\n";
$result = mysql_query("UPDATE accounts SET $key ='$data_n[1]' WHERE username = '$user'")
or
die(mysql_error());
Basically, there's a string "key" that is the name of the thing I'm trying to update, but it's just not updating. I've changed "mysql_query" to "print" and it prints out exactly what it's supposed to:
UPDATE accounts SET Total ='1144' WHERE username = 'derekboy'
There aren't any errors. printing out $result shows that it's "True" that it sent the message to MySQL. Can anyone see the problem, because I've been looking for a whole day and still nothing.
All of my code is located here; thanks. You can see that I connect to a database at the very top of the script.
1) You does not seem to have connected to mysql. Does your code do mysql_connect and mysql_select_db prior to this ?
2) Try running the query in the PHPMyAdmin (or whatever MySQL client you use) to see if there's any error or not. Does the query runs fine there ?
3) Most probably, there is no username with value derekboy in your table.
I don't know PHP particularly well, but it seems that you are surrounding the variables with single quotes, in which variables aren't interpolated.
Try something like:
$result = mysql_query("UPDATE accounts SET " . $key . " ='" . $data_n[1] . "' WHERE username = '". $user" . "'") or die(mysql_error());
Related
So, I'm using a database to store ship data.
As I load data into the database, I am checking whether the ship already exists. Sometimes, more than one ship has the same name. This code tries to go through the array, pull out all the ships with the same name, and then ask, in turn if that is the right one- if not, then it's yet another with the same name.
$sql = "SELECT Ship_Primary_Key, ship_original_rate, Ship_Launch_Year from Ships WHERE Ship_Name = '" . $shipname . "'";
$result = $conn->query ($sql);
if ($result-> num_rows > 0) //Does the ship name already exist in the DB? {
$ships_in_db = mysqli_fetch_all ($result,MYSQLI_ASSOC);
foreach ($ships_in_db as $row) {
echo "new record is " . $shipname . " as a " . $shiprate . ". Records already include " . $shipname . ", launched " . $row["Ship_Launch_Year"] . " as a " . $row ['ship_original_ra
$yesno = trim(fread(STDIN,5));
if ($yesno == "y" || $yesno == "yes") {
//ship already exists in the DB. Get the Key
echo $shipname . " is not new to the database and the key is " . $row["Ship_Primary_Key"] . "\n";
$shipkey = $row["Ship_Primary_Key"];
break 1;
}
}
//if you get through the loop of ships without assigning a primary key, ship is new
if (empty($shipkey)) {
$shipkey = write_ship_to_DB($shipname,$shiprate,$launchyear,$launchname,$conn);
}
}
So the problem is, I know that I have at least three ships with the same name in the first set of data (that are different). The problem is, it only ever asks about the first one. When I put 'n', it just goes on, and never asks about the second ship with the same name that already exists.
I think it's a problem with the Foreach loop and the break statement.
I'd appreciate any help with this
I've figured out the problem.
Because of the loop- I wasn't resetting the "Ship_Id" variable, which meant that the second or nth time a ship with the same name came around, a new ship wasn't created.
Now I've solved that. So the problem isn't this code at all- it's other code.
I am trying to get data out of my $result. When there is one result, it works fine. But when I want to check if there is a result and there is none I can't use $array anymore at all. If I run those both, they display nothing:
$query = "SELECT " . $select . " FROM " . $table . " WHERE `" . $field . "` = '" . $fieldis . "'";
$result = mysql_query($query) or die(mysql_error());
$array = mysql_fetch_assoc($result) or die(mysql_error());
if(!is_null($array)){echo "hahaha!";} else {echo "hahahahaha!";}
Result is no text at all. If I place an echo before the $array = mysql_fetch.... is works...What is messing with me here? :)
mysql_query don't raise an exception error, it raises a warning message instead. So die() will not be called.
However, the mysql library is deprecated, you should use mysqli.
See php documentation for further information at http://www.php.net
How can I make this script to where if it finds that the fname and lname do not exist that it will pop up a message saying that they never signed in.
<?php
session_start();
include_once("connect.php");
date_default_timezone_set("America/Winnipeg");
$date = ("m-d-Y");
$timeout = date("g:i:s a");
if ("SELECT EXISTS(
SELECT *
FROM signin_out
WHERE
lname='" . $_POST['lastname'] . "'
AND fname='" . $_POST['firstname'] . "'
AND date='" . $date . "')"
) {
mysql_query("
UPDATE signin_out
SET timeout='" . $timeout . "'
WHERE
lname='" . $_POST['lastname'] . "'
AND fname='" . $_POST['firstname'] . "'
AND timeout=''
");
header("Location: ../index.html");
} else {
echo "<script type='text/javascript>'";
echo "alert('<p>Oops! You never signed in!</p><br><p>Please contact a
Librarian</p>');'";
echo "</script>'";
header('Location: ../index.php?notsignedin');
}
?>
This is an intranet site for a highschool.
$sql = "SELECT COUNT(*) signedin FROM signin_out
WHERE lname = '" . mysql_real_escape_string($_POST['lastname']) . "'
AND fname = '" . mysql_real_escape_string($_POST['lastname']) . "'
AND date = '$date'";
$result mysql_query($sql) or die(myqsl_error());
$row = mysql_fetch_assoc($result);
if ($row['signedin'])) {
// update table
} else {
// Report not signed in
}
However, you really should switch to mysqli or PDO so you can use parametrized queries instead of concatenating strings, so you don't have to worry as much about escaping them.
This is only one part of the answer, #Barmar gave u how to handle the query itself.
Change
echo "<script type='text/javascript>'";
echo "alert('<p>Oops! You never signed in!</p><br><p>Please contact a
Librarian</p>');'";
echo "</script>'";
header('Location: ../index.php?notsignedin');
To
echo "<script type='text/javascript>'";
echo "alert('Oops!\nYou never signed in!\nPlease contact a
Librarian');'";
echo "window.location.href='../index.php?notsignedin';";
echo "</script>'";
The reason:
Strings which echo go into the web server buffer before being sent as a package to the browser.
This may cause your code to reach and do the header command, and then either you will redirect immediatly, or get an error message on the lines of '...you can not send headers after output...'
And seriously consider everybody's suggestion about PDO/Mysqli and using a more centralized/abstracted way to use the DB.
Check how many rows are returned by the query,if is more than 1 then fname and lname exists in database,you can also use count(*) but i won't to change your query :
$result = mysql_query("SELECT * FROM signin_out WHERE lname='".$_POST['lastname']."' AND fname='".$_POST['firstname']."' AND date='".$date);
$num_rows = mysql_num_rows($result);//count number of rows returned by query
if($num_rows >=1) {
//Update here
}
else {
//alert and redirect here
}
I understand that your site is for intranet use only , but i suggest to use PDO or Mysqli
After staring at these lines of code, and researching for hours on multiple coding forums, I am stuck with the code I have, which does not fully function. I am trying to successfully run this PHP script, so that a text quote can be queried randomly from a MySQL table and displayed in the footer of my website. The quote should change every time a user refreshes the Website. I am also trying to keep a count of how many times each quote is displayed, and then when a particular quote displays on my Website, a counter tell the site user how many times that particular quote has been displayed. My code thus far is:
<?php
include('Includes/inc_connect.php');
$DBName = 'database';
if (!#mysql_select_db($DBName, $DBConnect))
echo "<p style='text-align:center'>There are no quotes to view!</p>";
else {
$TableName = "randomquote";
$SQLstring = "SELECT quote FROM $TableName";
//executes the query
$QueryResult = #mysql_query($SQLstring, $DBConnect);
if ($QueryResult === false)
{
echo "<p>Unable to retrieve the data.</p>" . "<p>Error code: " . mysql_errno($DBConnect) . ": " . mysql_error($DBConnect) . "</p>";
}
else
{
$quote_array = array();//Creates a blank array
//use a while loop to extract the data from the database table into an indexed array
while(($Row = mysql_fetch_row($QueryResult)) !== FALSE)
{
$quote_array = $Row[0];
}
}
//assign the contents of the table to an array variable
$quote_count=count($quote_array);
$RandomArrayIndex = rand(0, $quote_count-1);
$quote = stripslashes($quote_array[$RandomArrayIndex]);
$SQLString = "UPDATE randomquote SET display_count " . " = display_count + 1 WHERE quote = " . $quote_array[$quote];
$SQLString = "SELECT display_count from randomquote WHERE quote = " . $quote_array[$quote];
$display_count = #mysql_query($SQLString, $DBConnect);
//display the random quote on the Web page
echo "<p style='text-align:center;font-style:italic'><strong>" . $quote . "</strong></p>\n";
echo "<p style='text-align:center>This quote has displayed " . $display_count . " times.</p>/n";
}
else
{
//specify that the comments cannot be read
echo "<p>The quote cannot be displayed at this time</p>\n";
}
else
{
//specify that there are no quotes
echo "<p>There are no quotes to display.</p>\n";
}
I am a student of both PHP and MySQL, so any and all help and advice is greatly appreciated. Thanks so much!
I believe this may help:
change
$SQLstring = "SELECT quote FROM $TableName";
to
$SQLstring = "SELECT quote FROM $TableName ORDER BY RAND()";
or if you only want one quote at a time
$SQLstring = "SELECT quote FROM $TableName ORDER BY RAND() LIMIT 1";
I am assuming here that your updating of the display count is working ok.
You could then drop the random array part of your code.
You can also think of an improvement - if I understand correctly what you are doing is fetching all of your quotes and then using php to randomly choose one . Why not use php to randomly choose a number (a quote id assuming your quote table has an id key ) and query only it ?
in pseudo code
$rand_post_id = rand(0,$num_of_quotes);
$query = "SELECT quote FROM $TableName WHERE quote_id=$quoteId";
$res = $mysql_query($query,$dbconnect);
And making sure you properly escape quote id which I didn't .
about my system the university complaint..stud or staff can use this system to complaint.
first user fill the form complaint and submit after submit user can view the complaint.now the problem is the complaint can't display....
this code for user complaint(userCampus.php):
?php // ------------------------------------------------------PROCESS -------------------------- START. ?>
<?php
$page_title='userCampus';
if(isset($_POST['submit'])){
if($_POST['secname']){
//$sn=escape_data($_POST['secname']);
$sn=$_POST['secname'];
// echo '<br> sn is : ' . $sn;
}else{
$sn=FALSE;
$message .='<p>You forgot to select section name!</p>';
}
if($_POST['subject']){
//$s=escape_data($_POST['subject']);
$s=$_POST['subject'];
}else{
$s=FALSE;
$message .='<p>you forgot to enter subject!</p>';
}
if($_POST['comment']){
//$c=escape_data($_POST['comment']);
$c=$_POST['comment'];
}else{
$c=FALSE;
$message .='<p>you forgot to enter comment!</p>';
}
}
if($sn && $s && $c ){
$userid = $_SESSION['username'];
$groupid = $_SESSION['secname'];
$query=" INSERT INTO campuscomplaint (secname, subject, comment, nameuser, groupid, userid)" .
" VALUES (" . "'" . $sn . "','" . $s . "','" . $c . "','" . $nameuser . "','" . $groupid . "','" . $userid . "')";
//echo 'query is : ' . $query . '<br>';
include "connectioncomplaint.php";
mysql_query($query);
echo'<p><b></b></p>';
include('done.php');
exit();
}
?>
<?php //------------------------------------------------ PROCESS ------------------------------------ end. ?>
<form action="<?php echo$_SERVER['PHP_SELF'];?>" method="post">
this code for view the complaint-userView.php(use for other page):
<?php //======================================================================================================================= PROCESS DATA ======================================================= START.
include "connectioncomplaint.php";
?>
<?php
$userid = $_GET['userid'];
$secname = $_GET['secname'];
$subject = $_GET['subject'];
$comment = $_GET['comment'];
//echo 'test : ' . $subject;
//Tarik data dari sini
$queryDetail = " SELECT * FROM campuscomplaint " .
" WHERE subject = '" . $subject . "' AND comment = '" . $comment . "' ";
//echo 'QUERY DETAIL :' . $queryDetail . '<br>' ;
$resultDetail = mysql_query($queryDetail);
//echo 'RESULT DETAIL :' . $resultDetail + 0 . '<br>' ;
$detail = mysql_fetch_array($resultDetail);
//echo $detail . '<br>';
//echo 'detail subject is : ' . $detail['subject'] . '<br>';
//echo 'detail comment is : ' . $detail['comment'] . '<br>';
//echo $detail[$x] . '<br>';
?>
i hope u all can help me....becoz i zero php.......
Let's see if we can check everything in on snip of code:
Paste the debugging code right after the line:
$detail = mysql_fetch_array($resultDetail);
Debugging code:
echo '<pre>';
echo '$userid = '.$userid."\n";
echo '$secname = '.$secname."\n\n";
echo 'Query: '.$queryDetail."\n\n";
echo 'Query results:'."\n\n";
print_r($detail);
echo '</pre>';
die();
That should make it clear where your problem is.
Also you should understand why you need to use mysql_real_escape_string() It's very important to make sure people don't do bad things to your website. Never send anything that can be changed by the user (such as GET or POST data) straight to a database without at least using this function. This escapes characters that would otherwise allow them to change your query (making it do something you don't want). To learn more about this google "sql injection attack"
one thing, from my experience. if something wrong with your query, just try it on mysql. ran your query in sql, and instead of your variables put some values, so you can easaly see what is your problem.
Looks like you forgot a $ sign before secname and you don't sanitize variables going to the query. So, try make it this way:
<?php
include "connectioncomplaint.php";
$userid = mysql_real_escape_string($_GET['userid']);
$secname = mysql_real_escape_string($_GET['secname']);
//Tarik data dari sini
$queryDetail = "SELECT * FROM campuscomplaint " .
"WHERE userid = '$userid' AND secname = '$secname'";
$resultDetail = mysql_query($queryDetail) or trigger_error(mysql_error()." in ".$queryDetail);
$detail = mysql_fetch_array($resultDetail);
?>
It looks you're not using a primary key on your campuscomplaint table, and using the various data fields as the identifier.
Since you say the data's inserted fine, you have to look at how you're retrieving it:
$userid = $_GET['userid'];
$secname = $_GET['secname'];
$subject = $_GET['subject'];
$comment = $_GET['comment'];
and then using these as your WHERE clause in the SQL query:
$queryDetail = " SELECT * FROM campuscomplaint " .
" WHERE subject = '" . $subject . "' AND comment = '" . $comment . "' ";
For one, this is vulnerable to SQL injection, and any $subject or $comment that contains single quotes will break the query. You are not checking to see if the query succeeded by calling mysql_error() after the mysql_query() call.
Also consider that you're retrieving these record "identifiers" from a GET query. These do have a limited length (different for various browsers). What if someone's comment is 10 kilobytes of data, but the browser will only send 1024 characters? Even if the database query succeeds, it will return no data because the comment fields will never match.
Let's say that the query string is limited to 100 characters (just for example purposes). You generate a list of complaints that looks something like this:
View complaint
Now remember, our query string is limited to 32 characters, so when the user clicks on the link, this is what will be sent to the server:
GET http://www.example.com/viewcomplaint.php?userid=7&secname=12&subject=This class sucks!!!&comment=Who hired this professor? He doesn't know a
and you'll end up with the following "identifiers"
$userid= 7;
$secname = 12;
$subject = "This class sucks!!!";
$comment = "Who hired this professor? He doesn't know a";
Notice how the $comment has been cut off. It will never match what is stored in the database, so your retrieval query will fail. Furthermore, notice that there is a single quote in it (doesn't). Inserting $comment into your query verbatim will now cause an SQL syntax error because of the imbalanced single-quote.
Add an auto_incrementing primary key field to your campuscomplaint table, like this:
ALTER TABLE campuscomplaint ADD id int unsigned not null auto_increment primary key;
and then all your complains can be identified by a single number, and you can retrieve them like this:
$id = (int)$_GET['id']; // force $id to be a number. better than just blindly using the value in a query
$query = "SELECT * FROM campuscomplaint WHERE id = $id;";
$result = mysql_query($query);
if (mysql_error()) {
// did the query fail? Say why!
die("MySQL query failed! Error cause: " . mysql_error());
}
etc....
The use of a numeric identifier will easily keep your query string very short (unless the people registering complaints file so many you get up into numbers hundreds or thousands of digits long).