What's wrong with the following syntax:
if( isset($_POST['save_changes']) ) {
// Get current id of customer
$currentID = $_GET['id'];
// Get Input Values
$newfirstName = validateInputData($_POST['first_name']);
$newlastName = validateInputData($_POST['last_name']);
$newemail = validateInputData($_POST['email']);
$newphone = validateInputData($_POST['phone_number']);
$newaddressOne = validateInputData($_POST['address_one']);
$newaddressTwo = validateInputData($_POST['address_two']);
$newcounty = validateInputData($_POST['county']);
$newcity = validateInputData($_POST['city']);
$newzipCode = validateInputData($_POST['zip_code']);
$newprovince = validateInputData($_POST['province']);
$newstate = validateInputData($_POST['state']);
// Queries
$query = "UPDATE customers
SET
first_name='$newfirstName',
last_name='$newlastName',
email='$newemail',
phone='$newphone'
WHERE id='$currentID'
";
$conn->query($query) or die($conn->error.__LINE__);
$query = "UPDATE addresses
SET
address_one='$newaddressOne',
address_two='$newaddressTwo',
county='$newcounty',
city='$newcity',
province='$newprovince',
zip_code='$newzipCode',
state='$newstate'
WHERE customer_id='$currentID'
";
$conn->query($query) or die($conn->error.__LINE__);
// Bring user back to index
header("Location: index.php?alert=savechanges");
// Close connection to database
$conn->close();
}
the above query runs fine, but the row is not updated. all the field names are appropriate. When the query is tried in phpMyAdmin, row updated.
Please help, thank you.
Your validateInputData() function is not doing any validation. Hopefully it's doing some escaping, implying that you are assuming global scope for your database connection object. You didn't tell us what type of database object this is. Your error checking is poor. You don't do an explicit exit after the redirect.
Apart from that the sql looks ok.
Related
I am trying to migrate ~55K records from a mySQL server over to MongoDB. I can't do this via any of the easily accessible methods like JSON/CSV importing because the data storage method (the way it is structured) will be very different. Because of this, I have created a script in php that is designed to do this.
The issue I have been running into with this is that over large sets of data (not reproducible using smaller data sets even when the smaller set includes problem entries) the queries will occasionally report no data despite the entry existing. It absolutely exists because when php accesses that specific entry directly or it is included in a smaller data set, it works just fine. For instance, in the import to a text file, i only received ~42k/54k records.
In the echo I am receiving through the url the php file is called through, I am showing that the query is called the correct number of times, but there are many records that are showing as not existing, thus the answering echo is blank. The code is included below:
//Makes a connection to the database
$conn = makeConnection();
$filename = '/home/dbserverdownload.txt';
$file = fopen($filename, 'a');
$sql = "SELECT * FROM maintable ORDER BY ID DESC LIMIT 1";
$resultID = mysqli_query($conn, $sql);
$ID = mysqli_fetch_object($resultID);
echo $ID->ID;
//loops through the database and appends the data to the file as it goes
for($var=2; $var <= $ID->ID; $var++){
$sql1 = "SELECT * FROM servertable WHERE ID = '$var'";
$result1 = mysqli_query($conn, $sql1);
$values = mysqli_fetch_object($result1);
$id = $values->ID;
$ip = $values->IP;
$port = $values->port;
$running = $values->running;
$afk = $values->afk;
$gamemode = $values->gamemode;
$maxplayers = $values->maxplayers;
$spawnprotection = $values->spawnprotection;
$whitelist = $values->whitelist;
$enablequery = $values->enablequery;
$enablercon = $values->enablercon;
$rconpassword = $values->rconpassword;
$motd = $values->motd;
$achievements = $values->announceplayerachievements;
$allowflight = $values->allowflight;
$spawnanimals = $values->spawnanimals;
$spawnmobs = $values->spawnmobs;
$forcegamemode = $values->forcegamemode;
$hardcore = $values->hardcore;
$pvp = $values->pvp;
$difficulty = $values->difficulty;
$generatorsettings = $values->generatorsettings;
$levelname = $values->levelname;
$levelseed = $values->levelseed;
$leveltype = $values->leveltype;
$autosave = $values->autosave;
if($ip == "148.57.44.10"){
//if the server is server1
$servername = "server1".$port;
} else if ($ip == "165.108.22.199"){
//if the server is server2
$servername = "server2".$port;
} else{
$servername = "";
}
//Adds all content that was already gained to the JSON string
$startingContent = "{\"_id\":\"$servername\",
\"ip\":\"$ip\",
\"port\":\"$port\",
\"running\":\"$running\",
\"afk\":\"$afk\",
\"gamemode\":\"$gamemode\",
\"maxplayers\":\"$maxplayers\",
\"spawnprotection\":\"$spawnprotection\",
\"whitelist\":\"$whitelist\",
\"enablequery\":\"$enablequery\",
\"enablercon\":\"$enablercon\",
\"rconpassword\":\"$rconpassword\",
\"motd\":\"$motd\",
\"announceplayerachievements\":\"$achievements\",
\"allowflight\":\"$allowflight\",
\"spawnanimals\":\"$spawnanimals\",
\"spawnmobs\":\"$spawnmobs\",
\"forcegamemode\":\"$forcegamemode\",
\"hardcore\":\"$hardcore\",
\"pvp\":\"$pvp\",
\"difficulty\":\"$difficulty\",
\"generatorsettings\":\"$generatorsettings\",
\"levelname\":\"$levelname\",
\"levelseed\":\"$levelseed\",
\"leveltype\":\"$leveltype\",
\"autosave\":\"$autosave\"
}";
echo $startingContent."<br/>";
//This is the JSON data that will be passed to mongo
if(strlen($ip)>6){
if (fwrite($file, $startingContent) === FALSE) {
echo "Cannot write to file ($filename) with $startingContent";
exit;
}
}
}
I have also tried this with a query that pulls a significant number(all, half, a quarter, etc) of the results in one chunk instead of tons of individual queries. The end result of that experiment was that a variable number of records were updated (usually a seemingly random number between 400 and 4000) each time it was run. Does anyone have any idea why this might be occurring? If not, should I just make my own program to iterate over the CSVs that I can export from mySQL?
First of all, replace your query $sql = "SELECT * FROM maintable ORDER BY ID DESC LIMIT 1";
with this $sql = "SELECT MAX(ID) as ID FROM maintable"; for better performance.
Your problem here is that you probably has a query that return false, then your application dies. Let's say, for example, your loop tries to query ID=3, but there is no row in your database with this ID. Then the next lines throws a exception, that you are not seeing. You could use set display_errors=On in you dev machine php.ini.
Use this to check if your have results to fetch:
....
for($var=2; $var <= $ID->ID; $var++){
$sql1 = "SELECT * FROM servertable WHERE ID = '$var'";
$result1 = mysqli_query($conn, $sql1);
if($result) {
$values = mysqli_fetch_object($result1);
$id = $values->ID;
$ip = $values->IP;
....
I am helping in some PHP design for a friends text game and have come to a stump.
I have scheduled a cron job to call the following page / following code, which is working correctly
<?php require("connect.php"); ?>
<?php
$sql = "SELECT id, name, health FROM users";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
while($row = mysql_fetch_object($query)) {
$id = htmlspecialchars($row->id);
$name = htmlspecialchars($row->name);
$health = htmlspecialchars($row->health);
$sql = "SELECT * FROM property WHERE living='1' AND ownerid='$id'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
while($row = mysql_fetch_object($query)) {
$OwnerName = htmlspecialchars($row->ownername);
$OwnerID = htmlspecialchars($row->ownerid);
$RaidPropBonus = htmlspecialchars($row->raidperc);
$RaidPropMoney = htmlspecialchars($row->raidcash);
$PropertyLvl = htmlspecialchars($row->proplvl);
$Living = htmlspecialchars($row->living);
if($PropertyLvl == '5' && $Living == '1'){
if($health < '100'){
$result = mysql_query("UPDATE users SET health=$health + '1' WHERE id='$id'")
or die(mysql_error());
} else { }
} else { }
}
}
?>
Although this only works for ONE user only. I cannot understand why this is. Any other logged in / out accounts that have met the criteria have been ignored. I can maybe only think I am missing a loop? As the ID that is being met first is number 1 and it has stopped there?
Anybody advice at all maybe?
UPDATE - It seems correct I need to get a loop in there, but am so far failing to get this loop working correct. No matter where I seem to amend / add a loop it does not help. Please may somebody suggest anything?
UPDATE2 - As requested, updated with the new version of loop
For what I've understood, the loops should be made on the mysql_fetch_object that will get the each row from the query.
Take a look at the snippet
<?php
require("connect.php");
// here prepare the $userQuery (the one that fetches all users)
// then the first loop that will read each usew row
// AFAICT this should afect all script
while($userRow = mysql_fetch_object($userQuery))
{
// prepare data fetched from the $userQuery
// prepare the $propertyQuery (the one that fetches all properties of the user)
// then the second loop to read all user property rows
// and this will afect the updates
while($propertyRow = mysql_fetch_object($propertyQuery))
{
// prepare data fetched from $propertyQuery
// add logic here
}
}
?>
Also #Matthew Carpenter had a valid point, that mysql_* is deprecated, you should consider in using mysqli_*, or in my opinion take a look at PDO
I am new to PHP. I wanted to create a new record in another table but just one new variable gets returned. I've tried following:
$user_id = mysql_real_escape_string($_POST['user_id']);
$user_name = mysql_query("SELECT user_name FROM accept WHERE user_id=".$user_id." ");
$row1 = mysql_fetch_array($user_name);
$server = mysql_query("SELECT server FROM accept WHERE user_id=".$user_id." ");
$row2 = mysql_fetch_array($server);
$url = mysql_query("SELECT link FROM accept WHERE user_id=".$user_id."");
$row3 = mysql_fetch_array($url);
$lpoints = mysql_real_escape_string($_POST['lpoints']);
And my result is this.
First of all, combine your queries into one:
$user_id = mysql_real_escape_string($_POST['user_id']);
$user_info = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row = mysql_fetch_array($user_info);
$lpoints = mysql_real_escape_string($_POST['lpoints']);
In order to create a new record, you will need INSERT INTO, to change existing records use UPDATE.
When you're fetching info from the database, it will be an array so you will need to use it accordingly. So essentially, to use the variables it will be like this:
$row['user_name'] or $row['server'] etc..
Also, look into using mysqli instead. You will need to change your connection script and some other syntax but it needs to be done. mysql is deprecated, insecure, and future support is not there so you will need to change it later anyway.
You should use pdo or mysqli and here is your code;
$user_id = &$_POST["user_id"];
if($user_id){
$result = mysql_query("select user_name,server,link,lpoints from accept where user_id='".mysql_real_escape_string($user_id)."'");
/*You should use single quotes for escaping sql injection*/
if($result){
$vars = mysql_fetch_array($result);
if($vars){
list($username,$server,$link,$lpoints) = $vars;
}
else{
//do something with errors
}
mysql_free_result($result);
}
else{
//do something with errors
}
}
else{
//do something with errors
}
Try This-
$user_id = mysql_real_escape_string($_POST['user_id']);
$result = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row=mysql_fetch_array($result)
$row1=$row['user_name'];
$row2=$row['server'];
$row3=$row['link'];
$lpoints = mysql_real_escape_string($_POST['lpoints']);
Now you got what you wanted based on your requirement use the data to insert or update.
I currently have a relatively large HTML form (100+ fields). I want to take the data from that form and upload it to a mySQL database when the use hits submit. I have created the PHP code below and have been slowly adding fields and testing to see if the connection is successful. Everything was working through $skilled_nursing, but when I added the next set of values I am no longer successfully creating database entries. All of my echo commands are displayed and I am not getting failures in my error log, but the data is not being received in the database.
Can anyone see what is going wrong? I have checked multiple times for spelling errors, but I haven't seen any. I am wondering if I am somehow timing out with the connection or if I am trying to stick too many values into the execute command.
<?php
echo 'started ok';
// configuration
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "dbname";
$dbuser = "dbuser";
$dbpass = "userpass";
echo 'variables assigned ok';
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
echo 'connection established';
// new data
$facility_name = $_POST['facility_name'];
$facility_street = $_POST['facility_street'];
$facility_county = $_POST['facility_county'];
$facility_city = $_POST['facility_city'];
$facility_state = $_POST['facility_state'];
$facility_zipcode = $_POST['facility_zipcode'];
$facility_phone = $_POST['facility_phone'];
$facility_fax = $_POST['facility_fax'];
$facility_licensetype = $_POST['facility_licensetype'];
$facility_licensenumber = $_POST['facility_licensenumber'];
$facility_email = $_POST['facility_email'];
$facility_administrator = $_POST['facility_administrator'];
$skilled_nursing = $_POST['skilled_nursing'];
$independent_living = $_POST['independent_living'];
$assisted_living = $_POST['assisted_living'];
$memory_care = $_POST['memory_care'];
$facility_type_other = $_POST['facility_type_other'];
$care_ratio = $_POST['care_ratio'];
$nurse_ratio = $_POST['nurse_ratio'];
// query
$sql = "INSERT INTO Facilities (facility_name, facility_street, facility_county, facility_city, facility_state, facility_zipcode, facility_phone, facility_fax, facility_licensetype, facility_licensenumber, facility_email, facility_administrator, skilled_nursing, independent_living, assisted_living, memory_care, facility_type_other, care_ratio, nurse_ratio) VALUES (:facility_name, :facility_street, :facility_county, :facility_city, :facility_state, :facility_zipcode, :facility_phone, :facility_fax, :facility_licensetype, :facility_licensenumber, :facility_email, :facility_administrator, :skilled_nursing, :independent_living, :assisted_living, :memory_care, :facility_type_other, :care_ratio, :nurse_ratio)";
$q = $conn->prepare($sql);
$q->execute(array(':facility_state'=>$facility_name,
':facility_street'=>$facility_street,
':facility_county'=>$facility_county,
':facility_city'=>$facility_city,
':facility_state'=>$facility_state,
':facility_name'=>$facility_name,
':facility_zipcode'=>$facility_zipcode,
':facility_phone'=>$facility_phone,
':facility_fax'=>$facility_fax,
':facility_licensetype'=>$facility_licensetype,
':facility_licensenumber'=>$facility_licensenumber,
':facility_email'=>$facility_email,
':facility_administrator'=>$facility_administrator,
':skilled_nursing'=>$skilled_nursing,
':independent_living'=>$independent_living,
':assisted_living'=>$assisted_living,
':memory_care'=>$memory_care,
':facility_type_other'=>$facility_type_other,
':care_ratio'=>$care_ratio,
':nurse_ratio'=>$nurse_ratio));
echo 'query parsed';
?>
This doesn't exactly answer what's going wrong with your code, but it might help solve it.
I would do this a bit differently. You say that you have a lot of fields. Your code is likely to get very long and repetitive. Since it looks like your form field names already correspond with your table columns, I would do something more like this (not tested):
// get a list of column names that exist in the table
$sql = "SELECT column_name FROM information_schema.columns WHERE table_name = 'Facilities'";
$q = $conn->prepare($sql);
$q->execute();
$columns = $q->fetchAll(PDO::FETCH_COLUMN, 0);
$cols = array();
foreach ($_POST as $key=>$value)
{
// if a field is passed in that doesn't exist in the table, remove it
if (!in_array($key, $columns)) {
unset($_POST[$key]);
}
}
$cols = array_keys($_POST);
$sql = "INSERT INTO Facilities(". implode(", ", $cols) .") VALUES (:". implode(", :", $cols) .")";
$q = $conn->prepare($sql);
array_walk($_POST, "addColons");
$q->execute($_POST);
function addColons($value, &$key)
{
$key = ":{$key}";
}
This way, you could have 10, 100, or 1000 fields and this code won't have to change at all. You also reduce your chance for typo errors because there's only one place where the column name is specified. You don't have to worry about SQL injection on the column names because you check to make sure that the column exists before allowing it to be used in your query.
This does, of course, assume that all fields passed in via $_POST correspond with column names in your table. If this isn't the case, it may be easiest to just store those particular field values that aren't columns in separate variables and unset() them from the $_POST array.
i have a problem my script has three mysql_query which should be used after each other , i am trying to create a script that reserve tickets by changing their status from sold = "No" to "Yes", the script count the number of tickets user has entered on html form which give the server side a variable with number of tickets called = $tickets.
hint : this is such a model so no need for mysql injection security
here is my code :
//get ticket status
$eventTicket = mysql_query("SELECT eventTickets FROM beventreservation WHERE eventId = '$eventId'") or die(mysql_error());
$ticketrow = mysql_fetch_array($eventTicket) or die(mysql_error());
//test... which is working !
echo $ticketrow['eventTickets'];
//get classId from classes
$selectClass = mysql_query("SELECT classId FROM quotaclasses WHERE className = '$classes' AND eventFK = '$eventId'") or die (mysql_error());
$classrow = mysql_fetch_array($selectClass) or die(mysql_error());
//this var is to define which class the user used
$choosedClass = $classrow['classId'];
//test ... which did not work !!!
echo $classrow['classId'];
if ($ticketrow['eventTickets'] == "Yes")
{
for($counter=1;$counter<$numberOfTickets;$counter++)
{
$bookTicket = mysql_query("UPDATE unites SET ticketSold = 'Yes' WHERE businessreservationIdFk = '$eventId' AND classIDfk ='$choosedClass'") or die(mysql_error());
echo "ticket ". $counter . " done !";
}
}
the script doesn't fetch this syntax, and there is no errors showed on my page !
$classrow = mysql_fetch_array($selectClass) or die(mysql_error());
also , i tried to echo the variable $tickets after this syntax , it did not showed up, is there a problem to fetch more than mysql_query on the same script page ? tell me where do i go wrong here please .
Don't call die() in conjunction with a mysql_fetch_*() call. If there are no rows returned, mysql_fetch_array() returns FALSE, which triggers your die() and kills your script even though there was no error. Since you have already don error checking on $selectClass in the mysql_query() call, you know it has succeeded.
// This query returned no rows, but was successful syntactically and functionally.
$selectClass = mysql_query("SELECT classId FROM quotaclasses WHERE className = '$classes' AND eventFK = '$eventId'") or die (mysql_error());
Instead, test if rows were returned:
if (mysql_num_rows($selectClass) > 0) {
// Fetch and do other stuff
$classrow = mysql_fetch_array($selectClass);
$choosedClass = $classrow['classId'];
// etc...
// etc...
}
else {
// Do whatever you need to do if no rows return
}