How to hide Partial Data in PHP [closed] - php

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Eperimenting PHP just for fun, But As being newbie, I'm unable to understand curcial parts of PHP....Please help me to sort out this problem which I'm explaining by example :
Suppose
$sql = "SELECT id, text,uid FROM feeds WHERE uid='".$ud."' LIMIT 10";
$items = mysql_query($sql);
echo mysql_error();
if (#mysql_num_rows($items) > 0)
{
while ($item = mysql_fetch_array($items))
{
$feed = $item[1];
$nick = getnick($item[2]);
}
}
So I want to display like this :
3 Records with uid details...
jay,vicky, sumair and 17 others like this.
Please help me to get output of something like this !!
Thanks !!

I can't stretch this enougth,
DO NOT USE MYSQL_* API anymore. [Read this]
It is VULNERABLE, mysqli_* functions are just as similar very little difference.
And You already are doing the things required for that output mysql_num_rows() already gives the number of total result. So:
if (mysql_num_rows($items) > 0)
{
$count = mysql_num_rows($items);
echo $count." Records with uid details..."; //Display the count of records
$threeNameHolder = array; // Hold the first three names on this
while ($item = mysql_fetch_array($items))
{
$feed = $item[1];
$nick = getnick($item[2]);
if(count($threeNameHolder) < 3) {
$threeNameHolder[] = $nick;
} else break; // End the loop here
}
//Now display the name
echo implode(",", $threeNameHolder). " and ".($count - 3)." others like this.";
}
Safer and MYSQLi Version
if (mysqli_num_rows($items) > 0)
{
$count = mysqli_num_rows($items);
echo $count." Records with uid details..."; //Display the count of records
$threeNameHolder = array; // Hold the first three names on this
while ($item = mysqli_fetch_array($items))
{
$feed = $item[1];
$nick = getnick($item[2]);
if(count($threeNameHolder) < 3) {
$threeNameHolder[] = $nick;
} else break; // End the loop here
}
//Now display the name
echo implode(",", $threeNameHolder). " and ".($count - 3)." others like this.";
}

To understand the basics fundaments, I really recommend the official documentation PHP
http://www.php.net/manual/en/ref.mysql.php
A simple sample to execute a query and display the output:
$query = mysql_query("SELECT a, b FROM table_name WHERE c='".$something."' LIMIT 10");
$num_rows = mysql_num_rows($query);
$test = array(); // create a empty array
/* while there is result */
while ($item = mysql_fetch_array($items)){
$columnA = $item[0];// first column (a)
$columnB = $item[1]); // second column (b)
$test[] = $columnB; // push_back a item on array
}
echo $num_rows. " Records with **" . $something . "**...";
echo implode($test, ", ") . "and some text";

Related

How to avoid re-comparison of strings in following scenario?

My PHP code snippet is as follows:
$sql = " SELECT * FROM ".TBL_QUESTIONS." WHERE question_subject_id=".$subject_id;
$sql .= " AND question_topic_id=".$topic_id;
$this->mDb->Query($sql);
$questions_data = $this->mDb->FetchArray();
$questions = $questions_data;
$exclude_words = array('which','who','what','how','when','whom','wherever','the');
/*This loop removes all the words of $exclude_words array from all questions*/
foreach($questions as $index=>$arr) {
$questions_array = explode(' ',$arr['question_text']);
$clean_questions = array_diff($questions_array, $exclude_words);
$questions[$index]['question_text'] = implode(' ',$clean_questions );
}
/*Now the actual comparison of each question with every other question stats here*/
foreach ($questions as $index=>$outer_data) {
$questions_data[$index]['similar_questions_ids_and_percentage'] = Array();
$outer_question = $outer_data['question_text'];
$qpcnt = 0;
foreach ($questions as $inner_data) {
/*This is to avoid comparing the question with itself*/
if ($outer_data['question_id'] != $inner_data['question_id']) {
$inner_question = $inner_data['question_text'];
/*This is to calculate percentage of match between each question with every other question*/
/*In this loop I want single time comparison of each question with every other question Now it's getting repeated, please help me here*/
$same_chars = similar_text($outer_question, $inner_question, $percent);
$percentage = number_format((float)$percent, 2, '.', '');
/*If $percentage is >= $percent_match only then push the respective question_id into an array*/
if($percentage >= 50) {
$questions_data[$index]['similar_questions_ids_and_percentage'][$qpcnt]['question_id'] = $inner_data['question_id'];
$questions_data[$index]['similar_questions_ids_and_percentage'][$qpcnt]['percentage'] = $percentage;
$qpcnt++;
}
}
}
}
Actually I want to avoid the re-comparison in a inner foreach loop from above code.
For example suppose there are ten questions and each one is comparing with other all remaining questions. If Q. No.1 is compared with Q. No. 8 then again when the time comes for Q.8, it's getting compared with Q.1 again. I want to avoid this. I want that if Q.1 is compared with Q.8 then again it should not be compared with Q. No.1 when the turn for Q. 8 comes.
Can anyone please help me out in this regard? any kind of help would be hoghly appreciated.
Maybe you can update the second foreach to also get the index:
foreach ($questions as $inner_data) {
changed to:
foreach ($questions as $secondIndex=>$inner_data){
and just under it add:
if ($secondIndex <= $index)
continue;

PHP code not running successfully

My question is very simple. The code I have written here produces absolutely no output on the webpage. I've been at it all day and I'm sure that it's something very simple that I am being an idiot for missing. So I am appealing to your good-natured fresh eyes! If anyone can spot a reason why this isn't working, I'd be very grateful.
The premise:
This is a decision tree online survey that has the following conditions: if a user has already started the survey, it will find them in the database, find their last answered question and display the next one. But if they haven't started, it will display the first question.
All survey questions are held in the database as well as the decision tree logic (for instance, if the user chooses option 2 for question 1, they will be directed to question 3, not 2).
Please assume that for the moment, I am updating relevant info directly from the database and not automating it on the website.
Thanks :)
PHP:
<?php
//Find the latest question reached by the user for display on the page
$sql = mysql_query("SELECT QuestionNumberReached FROM User WHERE EmailAddress = '***'");
$sqlCount = mysql_num_rows($sql);
if ($sqlCount > 0) {
while ($row = mysql_fetch_array($sql)) {
$QuestionNumberReached = $row["QuestionNumberReached"];
}
}
?>
<?php
//Find the last question answered by the user from the database
$StartedQuery = mysql_query("SELECT LastQuestionAnswered FROM User WHERE EmailAddress = '***'");
//Count the number of rows that the query produces
$StartedQueryCount = mysql_num_rows($StartedQuery);
//If data is found, whether it be a number or null, define the value
if ($StartedQueryCount > 0) {
while ($row = mysql_fetch_array($sql)) {
$LastQuestionAnswered = $row["LastQuestionAnswered"];
//If the field has a value and is not null, find the next question from the database
if (!empty($LastQuestionAnswered)) {
//Find the User's ID and the ID of the last question answered
$sqlA = mysql_query("SELECT PKID, LastQuestionAnswered FROM User WHERE EmailAddress = '***'");
//If the operation produces an error, output an error message
if (!$sqlA) {
die('Invalid query for SQLA: ' . mysql_error());
}
//Count the number of rows output
$sqlACount = mysql_num_rows($sqlA);
//If rows exist, define the values
if ($sqlACount > 0) {
while ($row = mysql_fetch_array($sqlA)) {
$sqlAPKID = $row["PKID"];
$sqlALastQuestionAnswered = $row["LastQuestionAnswered"];
}
}
//Find the answer given by the user to the last answered question
$sqlB = mysql_query("SELECT Answer FROM Responses WHERE User = $sqlAPKID");
//If the operation produces an error, output an error message
if (!$sqlB) {
die('Invalid query for SQLB: ' . mysql_error());
}
//Count the number of rows output
$sqlBCount = mysql_num_rows($sqlB);
//If rows exist, define the values
if ($sqlBCount > 0) {
while ($row = mysql_fetch_array($sqlB)) {
$sqlBAnswer = $row["Answer"];
}
}
//Find the number of the next question to be answered based on the user's previous answer and the question they answered
$sqlC = mysql_query("SELECT NextQuestion FROM Answers WHERE QuestionNumber = $sqlALastQuestionAnswered AND PKID = $sqlBAnswer");
//If the operation produces an error, output an error message
if (!$sqlC) {
die('Invalid query for SQLC: ' . mysql_error());
}
//Count the number of rows output
$sqlCCount = mysql_num_rows($sqlC);
//If rows exist, define the values
if ($sqlCCount > 0) {
while ($row = mysql_fetch_array($sqlC)) {
$sqlCNextQuestion = $row["NextQuestion"];
}
}
//Find the question text pertaining to the ID of the next question that needs to be answered
$sqlD = mysql_query("SELECT QuestionText FROM Questions WHERE PKID = $sqlCNextQuestion");
//If the operation produces an error, output an error message
if (!$sqlD) {
die('Invalid query for SQLD: ' . mysql_error());
}
//Count the number of rows output
$sqlDCount = mysql_num_rows($sqlD);
//If rows exist, define the values
if ($sqlDCount > 0) {
while ($row = mysql_fetch_array($sqlD)) {
$SurveyStartedQuestionText = $row["QuestionText"];
}
}
//Set a string of information that will show the question number and question text as appropriate
$ToDisplay = '' . $QuestionNumberReached . ': ' . $SurveyStartedQuestionText . '<br /><br />Answer Text Here';
//If the value for QuestionNumberReached is null, the user has not started the survey
} else if (empty($LastQuestionAnswered)) {
//Find the question text of the first question in the survey
$sql3 = mysql_query("SELECT QuestionText FROM Questions WHERE PKID IN (SELECT FirstQuestion FROM Batch WHERE BatchNumber IN (SELECT BatchNumber FROM User WHERE EmailAddress = '***'))");
//Count the number of rows output
$sql3Count = mysql_num_rows($sql3);
//If rows exist, define the values
if ($sql3Count > 0) {
while ($row = mysql_fetch_array($sql3)) {
$SurveyNotStartedQuestionText = $row["QuestionText"];
}
}
//Set a string of information that will show the question number and question text as appropriate
$ToDisplay = '' . $QuestionNumberReached . ': ' . $SurveyNotStartedQuestionText . '<br /><br />Answer Text Here';
}
}
}
?>
HTML:
<body>
<?php
// Display the concatenated information that has been previously defined
echo $ToDisplay;
?>
</body>
This bit:
if ($StartedQueryCount > 0) {
probably evaluates to false, and there's no matching else tag that adds content.
Try changing:
}
?>
with:
}
else {
$ToDisplay = 'Error: no rows found to display!';
}
?>
Edit:
Also, this bit:
} else if (empty($LastQuestionAnswered)) {
Could be replaced with the more readable:
} else {
Since it does exactly the same thing.
And within your while loop, you are constantly redefining $ToDisplay, I assume this is wanted behaviour? Otherwise initialize the variable on top (before the while() loop) like so:
$ToDisplay = '';
And change the assignments within the loop to concatenations, like so:
$ToDisplay = 'text assignment';
To:
$ToDisplay .= 'text concat'; // look at the dot before =
Thank you for all your help! I really appreciate you all taking the time.
I finally realised what was wrong...
On Line 18 of my PHP code, I had the following:
while ($row = mysql_fetch_array($sql)) {
whereas it should of course have been this:
while ($row = mysql_fetch_array($StartedQuery)) {
Essentially I was calling the rows from the wrong query. And I feel a clot because of it!
Thanks again, everyone :)

php importing csv into database [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have a csv file with 65000 records which i need to import into my database.
I have tried following code but real slow.
Is they anyway I can do this faster.
#set_time_limit(1200);
$file = './csvFiles/aw_Products.csv';
$handle = fopen( $file , 'r');
while (($row = fgetcsv($handle)) !== false) {
if( is_integer($row[0]) || $row[0] != 0 )
{
$product = new Product();
$product->merchant_id = $row[0];
$product->merc_product_id = $row[1];
$product->product_id = $row[2];
$product->product_name = $row[3];
$product->product_desc = htmlentities($row[4]);
//$product->keywords = htmlentities($row[6]);
$product->category_id = $row[5];
$product->link_url = $row[6];
$product->image_url = $row[7];
$product->price = $row[8];
$product->delivery_cost = $row[9];
//$product->deliveryAvailable = $row[12];
//$product->deliveryDetails = $row[13];
//$product->valid_to = $row[14];
//$product->valid_from = ($row[3] == 'yes') ? 1 : 0;
if( Product::find_by_id( $row[0] ) )
$product->updateRecord();
else
$product->createRecord();
}
sleep (1);
}
fclose($handle);
sleep() is probably the culprit. But I am also wondering about this: Product::find_by_id() because it might be doing a SELECT query for every INSERT. You might think about making a single SELECT query to get all of the existing DB keys into a PHP array, then you can use *in_array()* to check whether to UPDATE or INSERT. Probably goes without saying, but you will want to add to the PHP array if you INSERT.
Give up sleep() and use prepared statements for mysql insert/updates.

php permalink like wordpress permalink [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
What i want to do is to create a permalink like system such as the wordpress permalink.
For example:
$value = 'abc';
if($query_result > 0){
$value = 'abc1'; // if exists check abc2, abc3, abc4, abc5, etc. etc.
} else{
return $value
}
The query results is a search for the number of rows $query_result = mysql_num_rows
At this moment i created this:
if(!empty($_POST['ajax'])){
if($_POST['ajax'] == 'pages'){
echo prettyName($_POST['title']);
}
}
function prettyName($string)
{
$echo = strtolower(str_replace(array(' ', ' '), '-', preg_replace('/[^a-zA-Z0-9 s]/', '', trim($string))));
$sql = "SELECT * FROM posts WHERE post_pretty = '".$echo."'";
$res = mysql_query($sql) or die (mysql_error());
$num = mysql_num_rows($res);
if($num){
$echo = $echo.'-'.pretty2($echo, $num);
}
return $echo;
}
function pretty2($echo,$num,$i = 1)
{
$sql = "SELECT * FROM posts WHERE post_pretty = '".$echo.'-'.$i."'";
$res = mysql_query($sql) or die (mysql_error());
$num = mysql_num_rows($res);
if($num){
$i++;
$i = pretty2($echo,$num,$i);
}
return $i;
}
What does it do:
check if $value ($_POST['title']) exists
convert to a prettystring (by example: a b c = a-b-c)
check if prettystring exists else +1 (by example: a-b-c exists, a-b-c-1 - a-b-c-9999)
loop prettystring until free name doesn't exists.
But what goes wrong is:
if i create a new Post for example:
new post 1 name = testpage // results in testpage
new post 2 name = testpage // results in testpage-1
new post 3 name = test-page // results in testpage-2 // should be test-page
if i create a new Post with to much whitespaces in it it also get's wrong what could i use to remove all the white spaces? Tried to user TRIM function but that didn't work. Or should i be using javascript to avoid that?
It will return abc if num rows are 0
$value = 'abc';
$query_result = mysql_query("SELECT * FROM `table`");
$num_result = mysql_num_rows($query_result);
if($num_result){
$value = 'abc1';
}
PS. try to use PDO for your next development. A good Tutorial
for your problem:
$query_result = mysql_query("SELECT `name` FROM `Table1` ORDER BY `name` DESC LIMIT 1");
$num_result = mysql_num_rows($query_result);
if($num_result){
$row = mysql_fetch_assoc($query_result);
$value = (int)str_replace('abc', '', $row['name']);
$value = 'abc'.($value+1);
}

PHP/MySQL pagination going wrong

Using PHP on my website linking to a library database in MySQL. The one area I can't seem to get right is the pagination of results. I've tried about twenty different code snippets and have the same problem each time - can't get more than the first page of results to display. Despite reading lots of forum posts on this one, can't get past it. My select query is slightly more complex in that several keywords can be combined and it is searching multiple fields. When results are displayed, they also pull data from different tables. I really hope someone can spot where I'm going wrong. Switch statement used dependent on which type of search the user requests, so the code for one case given below.
$term = trim($_REQUEST['term']);
$searchterm = mysql_real_escape_string($term, $link);
$index = $_REQUEST['index'];
switch ($index)
{
case "title":
$array = explode(" ", $searchterm);
$sql = "select identifier, title, publication_date from publication where";
foreach ($array as $key => $keyword) {
$sql .= " (title like '%$keyword%' or alternative_title like '%$keyword%')";
if ($key != (sizeof($array) - 1)) $sql .= " and ";
if ($key == (sizeof($array) - 1)) $sql .= " order by title";
}
if(!$result = mysql_query($sql, $link)) {
showerror();
}
else {
$numrows = mysql_num_rows($result);
if ($numrows == 0) {
echo "<h2>No records found</h2>";
}
//start pagination
$perPage = 10;
$page = (isset($_REQUEST['page'])) ? (int)$_REQUEST['page'] : 1;
$startAt = $perPage * ($page - 1);
$totalPages = ceil($numrows / $perPage);
$links = "";
for ($i = 1; $i <= $totalPages; $i++) {
$links .= ($i != $page ) ? " <a href='search.php?page=$i&search=$term'>
Page $i</a> " : "$page ";
}
echo "<h3>Displaying page $page of $totalPages:</h3><br />";
$counter = 1;
$sql = "select identifier, title, publication_date from publication where";
foreach ($array as $key => $keyword) {
$sql .= " (title like '%$keyword%' or alternative_title like '%$keyword%')";
if ($key != (sizeof($array) - 1)) $sql .= " and ";
if ($key == (sizeof($array) - 1)) $sql .= " order by title
LIMIT $startAt, $perPage";
}
$result = mysql_query($sql, $link);
echo "<table class=\"results\">\n";
while($row = mysql_fetch_array($result))
{
//echo data
}
echo "</table><br />\n";
echo $links; // show links to other pages
echo "<p> </p>";
}
break;
as stated above, -1 vote for placing someone elses code instead of trying it yourself. This code is wayyyy to much for what a pagination script should do. You could have added more specific code snippet and a better question. I'll try to take a look at it however.
As you can't get further than page 1 it seems that somethings going wrong aroung $page = (isset($_REQUEST['page'])) ? (int)$_REQUEST['page'] : 1 ; or a little below. Try echoƫing your SQL code for each page and take a look if the LIMIT is right or that it stays the same, probably the last. At least that gives you a starting point from where to take a look in your code.
Does it give you the right amount of links to go to?

Categories