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
}
Related
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.
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I am attempting to implement a click count system. I am using the following code in this link Click here to see code, but changing it to modern standards. Initially I received errors for the msqli_real_escape_ string, but I believed I resolved it(no errors). Now, I am not receiving any errors at all, but the query is not sending into my database. I am using ini_set('display_errors', 1);
error_reporting(E_ALL); for error checking. Also I have my $con and session in and ini file that I call, so the session and connection are not issues.
Does anyone see what I am doing wrong or is there a good way I can check to see what isn't working?
//create current page constant
$curPage = mysqli_real_escape_string($con,htmlspecialchars($_SERVER['PHP_SELF']));
//set number of clicks variable to 0
$clicks = 0;
//do not recount if page currently loaded
if($_SESSION['page'] != $curPage) {
//set current page as session variable
$_SESSION['page'] = $curPage;
$click_sql = "
SELECT *
FROM click_count
WHERE page_url = ?
";
if (!$click_stmt = $con->prepare($click_sql)) {
$click_stmt->bind_param("s", $curPage);
$click_stmt->execute();
$num_rows = $click_stmt->fetchColumn();
if (!$click_stmt->errno) {
// Handle error here
}
$stmt->bind_result($click_id, $page_url, $page_count);
} elseif ($num_rows == 0) {
//try to create new record and set count for new page to 1
//output error message if problem encountered
$click_insert_stmt = "
INSERT INTO click_count
(page_url, page_count)
VALUES(?, ?)";
if(!$click_stmt = $con->prepare($click_insert_stmt)) {
$click_insert_stmt->execute(array('$curPage',1));
echo "Could not create new click counter.";
}
else {
$clicks= 1;
}
} else {
//get number of clicks for page and add 1 fetch(PDO::FETCH_BOTH)
while($click_row = $click_insert_stmt->fetch(PDO::FETCH_BOTH)) {
$clicks = $row['page_count'] + 1;
//update click count in database;
//report error if not updated
$click_update_stmt = "
UPDATE click_count
SET page_count = ?
WHERE page_url = ?
";
if(!$click_stmt = $con->prepare("$click_update_stmt")) {
$click_update_stmt->execute(array('$clicks', '$curPage'));
echo "Could not save new click count for this page.";
}
}
}
}
Edit: New Updated Code
// ********Page count************
//create current page constant
$curPage = mysqli_real_escape_string($con,($_SERVER['PHP_SELF']));
//set number of clicks variable to 0
$clicks = 0;
//do not recount if page currently loaded
if($_SESSION['page'] != $curPage) {
//set current page as session variable
$_SESSION['page'] = $curPage;
$click_sql = "
SELECT *
FROM click_count
WHERE page_url = ?
";
if (!$click_stmt = $con->prepare($click_sql)) {
$click_stmt->bind_param("s", $_SERVER['PHP_SELF']);
$click_stmt->execute();
$num_rows = $click_stmt->fetchColumn();
if (!$click_stmt->errno) {
// Handle error here
}
$stmt->bind_result($click_id, $page_url, $page_count);
} elseif ($num_rows == 0) {
//try to create new record and set count for new page to 1
//output error message if problem encountered
$click_insert_stmt = "
INSERT INTO click_count
(page_url, page_count)
VALUES(?, ?)";
if(!$click_stmt = $con->prepare($click_insert_stmt)) {
$click_insert_stmt->execute(array($curPage,1));
echo "Could not create new click counter.";
}
else {
$clicks= 1;
}
} else {
//get number of clicks for page and add 1 fetch(PDO::FETCH_BOTH)
while($click_row = $click_insert_stmt->fetch(PDO::FETCH_BOTH)) {
$clicks = $row['page_count'] + 1;
//update click count in database;
//report error if not updated
$click_update_stmt = "
UPDATE click_count
SET page_count=page_count+1
WHERE page_url = ?
";
if(!$click_stmt = $con->prepare("$click_update_stmt")) {
$click_update_stmt->execute(array($curPage));
echo "Could not save new click count for this page.";
}
}
}
}
It looks like you're doing a lot of stuff like this:
$click_update_stmt->execute(array('$clicks', '$curPage'));
I'm not sure where you picked up this habit of quoting variables as strings, but you need to drop it. '$x' and $x are two hugely different things. In the first case it's literally '$x' and in the second case it's whatever the $x variable happens to represent.
Fix it like this:
$click_update_stmt->execute(array($clicks, $curPage));
Also since you're using prepared statements, which by the way is great, you do not need to and should not manually escape your values. Applying them to placeholders with bind_param is the safe way of doing it. Doing any other escaping mangles the data.
Just bind directly to the source:
$click_stmt->bind_param("s", $_SERVER['PHP_SELF']);
Don't arbitrarily run things like htmlspecialchars on input out of paranoia or because you're doing cargo-cult programming and you saw it done in a YouTube tutorial somewhere. That function is intended to be used to display values only, not store them. Data in your database should be as raw as possible.
There's a lot of problems with this code, and one of them that has me confused is why there's so much code. Remember SELECT * and then binding results to arbitrary variables is trouble, your schema might change and then your code is out of sync. Whenever possible fetch rows as an associative array if doing this, then all you have to worry about is renamed ore removed columns.
The biggest problem is this is subject to race conditions because it doesn't use an atomic increment. When writing counters, always do your updates as operations that are a single statement:
UPDATE click_count SET page_count=page_count+1 WHERE page_url=?
Your approach of reading the count, incrementing it, and then writing it back into the database means that you're inviting problems if another operation runs concurrently, something very likely on click-counter code.
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
How to perform that loop:
while ($row = mysql_fetch_array($result)) {
collectData($row['NAME']);
}
To not freeze my PHP after 30 seconds?
I think it can be done by taking whole Database into array or *.temp file to work with it, not to connect everytime I want to input/output something. But I have problems with files and arrays, so thats why I am asking: whats the better/best way to do it fast and painless?
<?php
//fiveMin - Database that data is taken form
//HighCharts - Database that data is transferred to
$fiveMin=mysql_connect($fiveMin_host,$fiveMin_user,$fiveMin_pass);
mysql_select_db($fiveMin_db,$fiveMin) or die (mysql_error());
$query="SELECT * FROM BetterShopItemStock";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
collectData($row['NAME']);
}
function collectData($itemID) {
global $fiveMin_host, $fiveMin_user, $fiveMin_pass, $fiveMin_db, $week_host, $week_user, $week_pass, $week_db;
$fiveMin=mysql_connect($fiveMin_host,$fiveMin_user,$fiveMin_pass); //Load and store data from fiveMin Database
mysql_select_db($fiveMin_db,$fiveMin) or die (mysql_error());
$function_Query="SELECT AMT FROM BetterShopItemStock WHERE NAME = '$itemID'";
$function_Ask = mysql_query($function_Query);
$function_Result = mysql_fetch_row($function_Ask, 0);
$dataReadyToImport = "," . $function_Result[0];
#mysql_close($fiveMin);
$HighCharts=mysql_connect($week_host,$week_user,$week_pass); //Save stored data to weekly Database
mysql_select_db($week_db,$HighCharts) or die (mysql_error());
$function_Query="SELECT AMT FROM BetterShopItemStock WHERE NAME = '$itemID'";
$function_Ask = mysql_query($function_Query);
$function_Result = mysql_fetch_row($function_Ask, 0);
$storedData = $function_Result[0];
$dataReadyToImport = $storedData . $dataReadyToImport;
mysql_query("UPDATE BetterShopItemStock SET AMT='$dataReadyToImport' WHERE NAME='$itemID'");
#mysql_close($HighCharts);
}
?>
(1) You don't have to open and close a connection for every query - open one connection to each server and make multiple mysql_query() calls to them. That should speed you up quite a bit.
(2) Don't use "SELECT * FROM BetterShopItemStock" ... only select the row you need. (here, 'NAME'). And if you are already querying that table for 'NAME', then select 'AMT' at the same time, rather than making a second call to it.
(3) You can combine your select and update calls to HighCharts into a single query.
Altogether, everything should look something like this:
<?php
//fiveMin - Database that data is taken form
$fiveMin=mysql_connect($fiveMin_host,$fiveMin_user,$fiveMin_pass);
mysql_select_db($fiveMin_db,$fiveMin) or die (mysql_error());
//HighCharts - Database that data is transferred to
$HighCharts=mysql_connect($week_host,$week_user,$week_pass); //Save stored data to weekly Database
mysql_select_db($week_db,$HighCharts) or die (mysql_error());
$query="SELECT NAME,AMT FROM BetterShopItemStock";
$result = mysql_query($query,$fiveMin);
while ($row = mysql_fetch_row($result)) {
collectData($row[0],$row[1],$HighCharts);
}
function collectData($itemID, $itemAmt, $mysql) {
$id = mysql_real_escape_string($itemID);
$amt = mysql_real_escape_string($itemAmt);
$q = "UPDATE BetterShopItemStock SET ".
"AMT=CONCAT(AMT,',','$amt') WHERE NAME='$id'";
$r = mysql_query($q,$mysql);
return (!$r ? false : true);
}
//now close the databases
#mysql_close($HighCharts);
#mysql_close($fiveMin);
?>
(4) Lastly, if you are having execution timeout errors, look into PHP's set_time_limit to extend your execution time
Separate each one into classes and work with them after. It makes them run more efficiently and the querys do not intermesh:
<?php
class class1{
function fivemin(){
**code0**
}
function collectdata1-fivemin() {
class1::fivemin();
**code**
}
function collectdataHighcharts(){
class1::fivemin();
**code2**
}
}
$a = new class1;
$a->collectdata1-fivemin();
$a->collectdata1HighCharts();
?>
The following function is designed to check whether this row in this tables exists. I know that it does not yet whether I $row or !$row the if function it does not do anything.
function four_zero_four($name){
$four_zero_four = mysql_query("SELECT * FROM pages WHERE name = '$name'");
while($row = mysql_fetch_array($four_zero_four)) {
echo 'no'; die();
}
};
$name is the name field from the row and is working correctly in other functions.
Another way to check whether a row exists is by using the mysql_result function in conjunction with the COUNT function as such:
$query = mysql_query("SELECT COUNT(1) FROM `table` WHERE `field` = 'something'");
$result = mysql_result($query, 0);
When you now print out the $result variable, you will see the amount of rows that are actually being returned by the query. This is generally faster than using mysql_num_rows.
I'm not sure I understand the logic, aren't you printing "no"; die() when there IS a row found, instead of when now row is found? Either way, here's how I would check:
function four_zero_four($name){
$four_zero_four = mysql_query("SELECT * FROM pages WHERE name = '$name'");
if (mysql_num_rows($four_zero_four) == 0) {
// ROW DOES NOT EXIST
} else {
// ROW EXISTS
}
};
Your code does not work because it wont even be executed if there is no row returned by your query.
Use mysql_num_rows() instead:
$count = mysql_num_rows($four_zero_four);
if($count <= 0){
die("no rows in this table!");
}
Also, you should maybe consider to use MYSQLi commands instead of the old mysql_query() implementation and SELECT *, as they are deprecated.