I have following issue. I am parsing an xml feed with multiple pages and there is no way to understand how many they are (I have a variavle set in the xml url, so for each variable there are random number of pages). All I know is that the number can not exceed 50. Now I have a script that autoincrement the variable for the page number starting at 1 and up to 50.
Let's say, that the link has total of 26 pages. With my script I will continue to send requests until the scripts gets to page 50. Than it changes the first variable and starts again from 1 to 50. For the first link, from page 27 forward the xml will return followwing:
<response>
<status>error</status>
<code>400</code>
<message>Incorrect Request Headers</message>
</response>
How can I make so when the scipt receive this message, to stop the autoincrement and continue by changing the first variable and start again at 1? The code now is:
$query = "SELECT * FROM table_name ORDER BY id ASC";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
if($row['row_name'] == '') {
$variable1 = 0;
}
else {
$variable1 = $row['row_name'];
}
$page = 0;
do {
$page++;
$result = apiCall('option1', 'option2', array('option3' => $variable1, 'page' => $page));
usleep(1000);
$res = json_decode($result);
foreach ($res->node1->node2 as $item) {
//define variable for insertion in MySQL
$sql1 to insert the variables
if (!mysql_query($sql1,$con1))
{
die('Error: ' . mysql_error());
}
}
}
while ($page<=50);
}
In the above code, only the $variable1 and $page are variables. All options (1, 2 and 3) are predefined and stay the same. I.e. I need when the script gets the error message to start again from 1 with next value of $variable1.
OK. Here is the code I played around:
$query = "SELECT * FROM table_name ORDER BY id ASC";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
if($row['row_name'] == '') {
$variable1 = 0;
}
else {
$variable1 = $row['row_name'];
}
$page = 1;
do {
$result = apiCall('option1', 'option2', array('option3' => $variable1, 'page' => $page));
usleep(1000);
$res = json_decode($result);
if ($res->status == 'error') {
break 2;
}
foreach ($res->node1->node2 as $item) {
//define variable for insertion in MySQL
$sql1 to insert the variables
if (!mysql_query($sql1,$con1))
{
die('Error: ' . mysql_error());
}
}
$page++;
}
while (0);
}
The problem is that it stops the script execution at some point. Can not understand why.
Related
I have the below PHP code which picks up the posted form data from another file, executes SELECT queries to find all related data form the various tables (SalesDB, CustDB and ProdDB), and then executes an INSERT INTO query to add a row into the 'SalesDB' table. The form has dynamically added rows, which gives each newly added row a unique ID, for example:
...<input type="text" id="prodName_1" name="prodName[]" value="">
...<input type="text" id="prodName_2" name="prodName[]" value="">
.
.
...<input type="text" id="prodName_Z" name="prodName[]" value="">
However, when the PHP script runs for e.g. 3 rows of product lines, it only executes the $queryinsert query for the first iteration and inserts the first product line of the form. Why won't it loop through the array? See the php script below:
<?php
$db = new SQLite3('../xxx.db');
if(!$db){
echo $db->lastErrorMsg();
exit;
}
if (empty($_POST['custID'])) {
$errorMSG = array("No customer selected");
echo json_encode($errorMSG, JSON_PRETTY_PRINT);
exit;
} else {
$custID = $_POST['custID'];
$queryInsert = $db->prepare("INSERT INTO 'SalesDB'
(SalesID,CustID,ProdID,ProdQty,ProdPrice,ProdCurr,ProdVAT,SalesPrice,SalesVAT,SalesSum)
VALUES (?,?,?,?,?,?,?,?,?,?)");
$queryInsert->bindParam(1,$salesID);
$queryInsert->bindParam(2,$custID);
$queryInsert->bindParam(3,$prodID);
$queryInsert->bindParam(4,$prodQty);
$queryInsert->bindParam(5,$prodPrice);
$queryInsert->bindParam(6,$prodCurr);
$queryInsert->bindParam(7,$prodVAT);
$queryInsert->bindParam(8,$salesPrice);
$queryInsert->bindParam(9,$salesVAT);
$queryInsert->bindParam(10,$salesSum);
$querySalesID = "SELECT MAX(SalesID) AS max_SalesID FROM 'SalesDB'";
$resultSalesID = $db->query($querySalesID);
while ($row = $resultSalesID->fetchArray()) {
$salesID = $row['max_SalesID'] + 1;
}
foreach($_POST['prodName'] as $prodName => $value) {
if (!$value) {
$errorMSG = array("Empty product fields");
echo json_encode($errorMSG, JSON_PRETTY_PRINT);
exit;
} elseif ($value == "Product not found") {
$errorMSG = array("Invalid products in order form");
echo json_encode($errorMSG, JSON_PRETTY_PRINT);
exit;
}
$queryProd = "SELECT * FROM `ProdDB` WHERE ProdName LIKE '%$value%'";
$resultProd = $db->query($queryProd);
while ($row = $resultProd->fetchArray()) {
$prodID = $row['ProdID'];
$prodPrice = $row['ProdPrice'];
$prodQty = $row['ProdQty'];
$prodVAT = $row['ProdVAT'];
$prodCurr = $row['ProdCurr'];
$salesPrice = $prodQty * $prodPrice;
$salesVAT = number_format($prodQty * $prodPrice * $prodVAT,2);
$salesSum = $salesPrice + $salesVAT;
}
$result = $queryInsert->execute();
}
}
?>
Please also note that I am aware that I am (most likely) making a lot of mistakes when it comes to security practices or programming standards, but this whole thing (PHPDesktop > https://github.com/cztomczak/phpdesktop) will get packed into an EXE file which will run locally only (no need for an online connection as the SQLite3 DB gets packed in with the EXE), and I am still figuring out how to program this in the first place, so efficient and tidy coding are not high on my list yet ;-)
There are some issues in the script:
1) Instead of doing exit inside the foreach, do continue to skip the single actual iteration.
As in the official documentation:
continue is used within looping structures to skip the rest of the
current loop iteration and continue execution at the condition
evaluation and then the beginning of the next iteration.
Try this code:
foreach($_POST['prodName'] as $prodName => $value) {
if (!$value) {
$errorMSG = array("Empty product fields");
echo json_encode($errorMSG, JSON_PRETTY_PRINT);
continue;
} elseif ($value == "Product not found") {
$errorMSG = array("Invalid products in order form");
echo json_encode($errorMSG, JSON_PRETTY_PRINT);
continue;
}
$queryProd = "SELECT * FROM `ProdDB` WHERE ProdName LIKE '%$value%'";
$resultProd = $db->query($queryProd);
while ($row = $resultProd->fetchArray()) {
$prodID = $row['ProdID'];
$prodPrice = $row['ProdPrice'];
$prodQty = $row['ProdQty'];
$prodVAT = $row['ProdVAT'];
$prodCurr = $row['ProdCurr'];
$salesPrice = $prodQty * $prodPrice;
$salesVAT = number_format($prodQty * $prodPrice * $prodVAT,2);
$salesSum = $salesPrice + $salesVAT;
}
$result = $queryInsert->execute();
}
2) your query are using user inputs without check their contents, so your script maybe open to SQLInjection!
$queryProd = "SELECT * FROM `ProdDB` WHERE ProdName LIKE '%$value%'";
3) if the query does return nothing, the script does not enter in the while loop, so it seems that the foreach do only one iteration but instead it do all iterations without enter in the while because of empty result from that query.
I suggest to you to debug all pieces of your code by printing out variables content using var_dump, e.g.:
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
I've tried like twenty times and the closest I got was when I put in a variable stored in row 1 of the db and it returned the content the last row in the db. Any clarity would be extremely helpful. Thanks.
// Create connection
$coco = mysqli_connect($server, $user, $pass, $db);
// Check connection
if (!$coco) { die("Connection failed: " . mysqli_connect_error()); }
// Start SQL Query
$grabit = "SELECT title, number FROM the_one WHERE title = 'on' AND (number = 'two' OR number='0')";
$result = mysqli_query($coco, $grabit);
// What I need it to do
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$titleit = $row["title"];
$placeit = $row["number"];
$incoming = 'Help';
if ($titleit[$_REQUEST[$incoming]]){
$message = strip_tags(substr($placeit,0,140));
}
echo $message;
}
} else {
echo "not found";
}
mysqli_close($coco);
Put the input that you want to match into the WHERE clause of the query, rather than selecting everything and then testing it in PHP.
$incoming = mysqli_real_escape_string($coco, $_POST['Help']));
$grabit = "SELECT number FROM the_one WHERE title = '$incoming' AND number IN ('two', '0')";
$result = mysqli_query($coco, $grabit);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['number'];
}
} else {
echo "not found";
}
I think you need to add a break; in that if or I would assume it would go through each row in the database and set message if it matches the conditional. Unless you want the last entry that matches...if not you should debug:
if ($titleit[$_REQUEST[$incoming]]){
// set message
}
and see when it's getting set. That may not be the issue, but it's at least a performance thing and could explain getting the last entry
Have you tried print_r($row) to see the row or adding echos to the if/else to see what path it's taking?
There is ALOT of code, but most of it is irrelevant, so i will just post a snippet
$error_message = "";
function died($error) // if something is incorect, send to given url with error msg
{
session_start();
$_SESSION['error'] = $error;
header("Location: http://mydomain.com/post/error.php");
die();
}
This works fine, sends the user away with a error session, which displays the error on the error.php
function fetch_post($url, $error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
This also works fine, checks if the "post" exists in the database, if it does, it adds the error the variable $error_message
while ($current <= $to) {
$dom = file_get_html($start_url . $current); // page + page number
$posts = $dom->find('div[class=post] h2 a');
$i = 0;
while ($i < 8) {
if (!empty($posts[$i])) { // check if it found anything in the link
$post_now = 'http://www.somedomain.org' . $posts[$i]->href; // add exstension and save it
fetch_post($post_now, &$error_message); // send it to the function
}
$i++;
}
$current++; // add one to current page number
}
This is the main loop, it loops some variables i have, and fetches posts from a exsternal website and sends the URL and the error_message to the function fetch_posts
(I send it along, and i do it by reference couse i asume this is the only way to keep it Global???)
if (strlen($error_message > 0)) {
died($error_message);
}
And this is the last snippet right after the loop, it is supposed to send the error msg to the function error if the error msg contains any chars, but it does not detect any chars?
You want:
strlen($error_message) > 0
not
strlen($error_message > 0)
Also, call-time pass-by-reference has been deprecated since 5.3.0 and removed since 5.4.0, so rather than call your function like this:
fetch_post($post_now, &$error_message);
You'll want to define it like this:
function fetch_post($url, &$error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
Although as you're returning the error message within a loop it would be better to do this:
$error_messages = array();
// ... while loop
if ($error = fetch_post($post_now))
{
$error_messages[] = $error;
}
// ... end while
if (!empty($error_messages)) {
died($error_messages); // change your function to work with an array
}
I am showing an image on my page from the db table like this:
<?php
if ($db_found) {
$SQL = "SELECT * FROM myTable where id='$posted_id'";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
echo '<img src="images/'.$db_field['image'].'" alt="" />';
}
mysql_close($db_handle);
}
?>
Next
How can I do so that if $posted_id is for example 1 ... when I click the "Next" link the image id = 2 appears and so on.
for that you need to either refresh page or use ajax.
you can pass variable posted_id in url like this.
Next
this way you can pass next id from database .. if your id falls in sequence.
you also need to programatically handle issue like what to do if record of next id does't exist in database..
You should work with the MySQL LIMIT and ORDER filters.
<?php
if (isset($_GET['current'])) {
$current = $_GET['current'];
} else {
$current = 0;
}
$request = "SELECT * FROM myTable ORDER BY id ASC LIMIT " . $current . ",1";
?>
And then, just to catch the next item, you can do something like that:
<?php
// make the last item point to the first one
$loop = true;
$count = "SELECT COUNT(*) FROM myTable";
if ($current < $count) {
$next = $current + 1;
} else if ($loop) {
$next = 0;
// no loop, then just stay at the end
} else {
$next = $current;
}
?>
I have output from a select query as below
id price valid
1000368 69.95 1
1000369 69.94 0
1000370 69.95 0
now in php I am trying to pass the id 1000369 in function. the funciton can execute only if the valid =1 for id 1000368. if it's not 1 then it will throw error. so if the id passed is 1000370, it will check if valid =1 for 1000369.
how can i check this? I think it is logically possible to do but I am not able to code it i tried using foreach but at the end it always checks the last record 1000370 and so it throws error.
regards
Use a boolean variable:
<?php
$lastValid=false;
while($row = mysql_fetch_array($result))
{
if ($lastValid) {
myFunction();
}
$lastValid = $row['valid'];
}
?>
(Excuse possible errors, have no access to a console at the moment.)
If I understand correctly you want to check the if the previous id is valid.
$prev['valid'] = 0;
foreach($input as $i){
if($prev['valid']){
// Execute function
}
$prev = $i;
}
<?php
$sql = "SELECT * FROM tablename";
$qry = mysql_query($sql);
while($row = mysql_fetch_array($qry))
{
if ($row['valid'] == 1)
{
// do some actions
}
}
?>
I really really recommend walking through some tutorials. This is basic stuff man.
Here is how to request a specific record:
//This is to inspect a specific record
$id = '1000369'; //**some specified value**
$sql = "SELECT * FROM data_tbl WHERE id = $id";
$data = mysql_fetch_assoc(mysql_query($sql));
$valid = $data['valid'];
if ($valid == 1)
//Do this
else
//Do that
And here is how to loop through all the records and check each.
//This is to loop through all of it.
$sql = "SELECT * FROM data_tbl";
$res = mysql_query($sql);
$previous_row = null;
while ($row = mysql_fetch_assoc($res))
{
some_action($row, $previous_row);
$previous_row = $row; //At the end of the call the current row becomes the previous one. This way you can refer to it in the next iteration through the loop
}
function some_action($data, $previous_data)
{
if (!empty($previous_data) && $condition_is_met)
{
//Use previous data
$valid = $previous_data['valid'];
}
else
{
//Use data
$valid = $data['valid'];
}
if ($valid == 1)
{
//Do the valid thing
}
else
{
//Do the not valid thing
}
//Do whatever
}
Here are some links to some good tutorials:
http://www.phpfreaks.com/tutorials
http://php.net/manual/en/tutorial.php