I am trying to write a custom script that will keep a list of strings in a textarea. Each line of the textarea will be a row from a table.
The problem I have is how to work the script to allow for adding, updating, or deleting rows based on a submit.
So, for instance, I currently have 3 rows in the database:
john
sue
mark
I want to be able to delete sue and add richard and it will delete the row with sue and insert a row for richard.
My code so far is as follows:
To query the db and list it in the textarea:
$basearray = mysql_query("SELECT name FROM mytable ORDER BY name");
<textarea name="names" cols=6 rows=12>');
<?php
foreach($basearray as $base){
echo $base->name."\n";
}
?>
</textarea>
After the submit, I have:
<?php
$namelist = $_REQUEST[names];
$newarray = explode("\n", $namelist);
foreach($newarray as $name) {
if (!in_array($name, $basearray)) {
mysql_query(DELETE FROM mytable WHERE word='$name'");
} elseif (in_array($name, $basearray)) {
;
} else {
mysql_query("INSERT INTO mytable (name) VALUES ("$name")");
}
}
?>
Please tell me what I am doing wrong. I am not getting any functions to work when I edit the contents of the textarea.
Thanks!
The answer is simple. Don't do it using textarea. That's what you're doing wrong.
List your strings in HTML table, with "Edit" and "Delete" buttons.
Edit your rows by one and you'll never have any problem.
As for your approach to treat a database as a plain text file, be consistent and think of it as a plain text file. So, it must be emptied before writing.
Edit:
Or - even much,much better - get rid of the database and use a txt file instead.
So, your code become as simple, as
<textarea name="names" cols=6 rows=12>');
<?php readfile('base.txt') ?>
</textarea>
and form handler is
<?php file_put_contents("data.txt",$_REQUEST['names']); ?>
Related
People can order links at my platform and these get stored in two different tables, eg wp_project and wp_articles. The reason for this is that when people place an order for 1 link one project row gets created and one article row gets created.
However if a client orders 10 links there will be one project entry and ten article entries. Now this isn't very relevant to my problem but just to explain how the system works.
There are two common identifiers for projects and articles, both the ID and the project title are stored in both inpu_project and inpu_articles.
Now if I want to echo all the links from one project I built a search function where I can select the project ID, click search and whether a client ordered 1 link or 20 links that amount of links will show.
The problem starts when I want to search based on the project title instead of ID, which is non-numeric but just words (with spaces in between sometimes).
This to prevent the error undefined index in my error logs
$where_clouse='';
This is the search function based on the project title:
if(isset($_GET['todo']) && $_GET['todo']=='search')
{
if($_GET['proid']!=0){
$where_clouse.=' AND P.`project_title`='.$_GET['proid'];
}
}
This is the database query to pull the links from it:
$sql="SELECT P.`project_title`, P.`backlink` FROM `inpu_articles` AS P
WHERE P.`post_it_posted` = '1' ".$where_clouse." ORDER BY P.`project_title` ASC";
$backlinks=$wpdb->get_results($sql, ARRAY_A);
This is the actual search function that triggers the first code I pasted:
<p>Select a project title and hit search!</p>
<form action="" method="get">
<input type="hidden" name="todo" id="todo" value="search" />
<select name="proid" id="proid">
<option value="0">All Projects</option>
<?php $projects=getTitles(); foreach($projects as $project){ ?>
<option value="<?php echo $project['title']; ?>" <?php if(isset($_GET['proid']) && $_GET['proid']==$project['title'] ) { echo 'selected="selected"'; } ?> ><?php echo $project['title'] ?>
</option>
<?php } ?>
</select>
<input class="submit_search" type="submit" id="search_button" value="Search"/>
</form>
And this is the code that pulls the project titles from the project table:
function getTitles($where=false)
{
global $wpdb;
$sql="SELECT `title`, `link` FROM `inpu_project` WHERE `link`='1' ORDER BY `title` ASC";
$result = $wpdb->get_results($sql, ARRAY_A);
return $result;
}
All pretty straight forward and it works 100% fine if I replace the non-numeric title in the code for both the inpu_articles and the inpu_project tables with the numeric id.
Then the code does exactly what it does, but when I use the project title instead it just shows ALL of the links that every client ever ordered and no error shows up in my database. It's like it can't find a match or something, which is plain weird.
So am I missing something here? Is it not possible to match words or is there something that I should adjust when using words instead of numeric values?
Lastly, for what it's worth, this is the code that echos the query:
<?php foreach ($backlinks as $backlink) {
$backlink_overview=$backlink['backlink'];
?>
<ul>
<li><?php echo $backlink_overview; ?></li>
</ul>
<?php } ?>
The titles do show up in my form / search drop down menu so I am surprised it can't match the project title with the title that's stored in the article table.
My gut says this is where it goes wrong:
P.`project_title`='.$_GET['proid'];
But it doesn't throw any syntax errors or any errors whatsoever, it just shows all the links that are stored in the inpu_article table, ignorning my search function altogether.
The problem is in the condition for where_clause and the where_clause itself.
To check for input you need to check if the parameter is set and is not empty. Then for where clause you need to put the string into quotes. Change that part of the code like bellow
if(isset($_GET['proid']) && !empty($_GET['proid'])){
$where_clouse.=" AND P.project_title='".$_GET['proid']."'";
}
i think you can be wrong in SQL statement. And you can print the sql string statement to the screen and copy it into Mysql to check. I hope you can find your mistake.
i am fetching different record from the database but using single quantity field trying to insert multiple records into MYSQL but every time for loop or any other loop overriding single value in all rows(inserting single first value in every field), badly stuck. kindly suggest what kind of appropriate steps should be done.
<input type="text" name="qty[]" id="qtyid" style="width:40px;">
<?php
if(isset($_POST["update"])) {
$usersCount=count($_POST['qty']);
$qtys=implode(",",$_POST['qty']);
for($i=0;$i<$usersCount;$i++) {
$query="UPDATE cart set qty='".$qtys."' WHERE prodid='$cartid'";
$dbh->query($query);
echo $qtys;
}
}
$total=$total*$qtys;
?>
Your "question" is unclear. I read it couple times nad i still dont know what is your problem.
Anyway. I'll try to explain what your code do in case it would help you to understand where the problem is.
//if form was submited and input of name "update" was in
if(isset($_POST["update"])) {
// count array created by inputs of name="qty[]"
$usersCount=count($_POST['qty']);
// make a string from that array, separating the keys by a "," char
$qtys=implode(",",$_POST['qty']);
// loop as many times as number of elements in that array = <input name="qty[]"> you had in submited form
for($i=0;$i<$usersCount;$i++) {
// and finally, do always the same for each loop repeat
$query="UPDATE cart set qty='".$qtys."' WHERE prodid='$cartid'";
$dbh->query($query);
echo $qtys;
}
}
So in conclusion your loop is doing always the same - every each repeat:
`$query="UPDATE cart set qty='".$qtys."' WHERE prodid='$cartid'";`
Basically to do that you would't need to have loop.
Because in that query you change value of column qty wherever column prodid is equal to something
I have worked on this for a few days now.
This snippet finds the correct row(s) from the database. It works fine. However, when the Button is clicked, I only want for the comment it is next to targeted, not all the comments on that page. It's hard to explain.. Let me show you image.
What I am doing currently is selecting the database rows and outputting them for debugging, instead of removing them (I don't want to go around deleting sections of my database with broken code)
$db is mysqli connection to the database
Snippet of the while loop:
TL/TR
I want to do the following with this in the end:
Remove the comment from the database.
Give the feedback to an admin.
This may sound like a noob question, but please help me.
Many thanks!
Just can't wrap my head around this, made like 6 pages single-handed and now I am stuck in a thing this "easy" for a d**n week and i still can't get it right.
EDIT
Latest snippet (Still doing it, What the hell!?!)
$query = $db->query("SELECT * FROM comments WHERE post_id='$id'");
while($row = $query->fetch_object()){
echo "<h5>".$row->name."</h5>","<br>";
$strip_comment = strip_tags($row->comment);
$delComment = $row->comment_id;
$strip_comment_shlashes = stripslashes($strip_comment);
echo "<blockquote>".$strip_comment_shlashes,"<br><br></blockquote>";
//button stuff
if($is_admin){
$query1 = $db->prepare("SELECT comment_id FROM comments WHERE comment_id = '$delComment'");
$query1->execute();
$query1->bind_result($commId);
while($row2 = $query1->fetch()):
?>
<form action="<?php echo $_SERVER['PHP_SELF']."?id=$id"?>" method="post">
<input type="submit" class="closeButton" name="deleteComment" value="<?php echo $commId; ?>" />
</form>
<?php
if(isset($_POST['deleteComment'])&& $is_admin){
if($is_admin && $commId){
echo "Comment ID <b>$commId</b> Removed";
}
}
endwhile;
}
Edit: NON-OBJECT error..
$delComment_2 = $_POST['deleteComment'];
$query2 = $db->prepare("SELECT * FROM comments WHERE comment_id='$delComment_2'");
$query2->execute();
Edit 2: (31/10)
Please, Could someone fix this snippet and post it? I don't usually ask for working snippets, but this one is driving me crazy. I just am too noob to understand how this goes. Thanks.
Change the input to this:
<input type="submit" class="closeButton" name="deleteComment" value="$comment_id_here" />
And then just use the comment id to delete a specific one from the database. (check $_POST['deleteComment'])
Of course, there are numerous other ways to do this - but the point is the same: you need to pass the comment id (not the post id) from your page to the query string. Whatever way you use to accomplish that is up to you, I just gave you an example.
How do I Limit some information displayed from the database and add a link eg "More" to enable read all information in a drop down using PHP. such as what is on facebook (Read more...). I am dealing with a lot of content and I dont want it all displayed at once.
Here is part of the code
echo "<p>".$row['Firstname']." ".$row['Lastname']."</p>";
echo "<p>".$row["Course"]." | ".$row["RegID"]."</p>";
echo "<p>".$row["Email"]."</p>";
echo "<p>"."Tel:".$row["Telephone"]."</p>";
echo "<p>".$row["info"]."</p>";
The code is running well only that I want to limit the information
echo "<p>".$row["info"]."</p>";
so that not all is displayed
Thanks
Use Jquery-ui click on "view source" and you'll see it's very simple really, just set the row that you want as the header (what's clicked to show the rest) and store the rest in a div below.
Split info into two strings, one intro, and the rest. Display only the intro to begin with. Insert a link that displays the rest when clicked.
$intro = substr($row['info'], 0, 200);
$rest = substr($row['info'], 200);
echo sprintf(
<<<HTML
<p>
<span class="intro">%s</span><span class="rest" class="display: none">%s</span>
Show more
</p>
HTML
, htmlentities($intro)
, htmlentities($rest)
);
displayRest is a Javascript-function that, given a link, finds the previous span with class rest, shows it and removes the link. I leave it as an exercise to implement this in a way that fits your project. You can go with native Javascript, or use a library such as jQuery, YUI, MooTools, Prototype etc.
if(isset($_POST['more']))
{
$query="select col1,col2,col3, ... ,colN from tableName ";
}
else
{
$query="select col1,col2,col3 from tableName ";
}
//HTML
<form method="post">
<input type="submit" name="more" value="More" />
</form>
//PHP
$records=mysql_query($query);
while($row=mysql_fetch_assoc($records))
{
//Display
}
The limit must be fixed on the SQL request.
// If you want to transmit limitation with a GET PARAMETER.
// You can also $_POST ur data.
$limitation = $_GET['limit'];
//..... And in your SQL REQUEST
$sql = "SELECT * FROM your_table LIMIT 0 , $limitation";
//And in the link....
echo 'Show only 10 Results'
?>
You can optimize that and add security precaution to prevent errors when $limitation receive empty or non numeric parameters.
<?php if(isset($_GET['limit']) && !empty($_GET['limit']) && !preg_match(EXPRESSION, $_GET['limit'])){
//YOU CAN DO THE LIMITATION WHITOUT SQL ERRORS
}
else{
//ERROR DIRECTIVE
}
?>
I want a function that prints those 2 "print" in the database ( insert intro ) when a button is pressed.
Here's the code:
<?php
$id2name=array();
$x=mysql_query("SELECT id,name FROM products WHERE id IN(".implode(',',array_keys($_SESSION['cart'])).")");
while($y=mysql_fetch_assoc($x)){
$id2name[$y['id']]=$y['name'];
}
foreach($_SESSION['cart'] as $k=>$v){
print "<br>[".$id2name[$k]."]\t".$v."\n <br>";
}
print "<br>$total<br>";
?>
How can I make that a function, to print it in the database when a button is pressed?
Not sure if I got you right, but as far as I understand, you want to write something to the database by pressing a button, right?
Well, to trigger an action by pressing a button, you need a form:
<form action="page_to_process_the_db_request.php" method="post">
<input type="hidden" value="<?php echo $total;?>" name="total" />
<input type="submit" value="Wirite to DB!" />
</form>
In this example, I assume you want to write the variable $total to DB.
So you post the data to the processing page (which also can be the same one you're on) and there, you look if there's something in the $_POST-array:
<?php
if(isset($_POST['total'])) {
mysql_query("UPDATE products SET total = ". $total); //or something like that
}
?>
Not sure though if this is what you're looking for...
//edit
referring to your comment, I guess you want to write the output of the loop to DB...
At first, you have to create an appropriate structure, like an array:
foreach($_SESSION['cart'] as $k=>$v){
$id2name[$k]['name'] = $v;
}
now you can turn the array into a simple string with
$serialized_array = serialize($id2name);
And now you can write this string to db. And when you read it from db, you can turn it back into an array again with:
$id2name_array = unserialize($serialized_array);