how to explode array with certain key in php - php

I'm developing an app about books and I had a table for contents. before, I made a mistake and I split content in myself and insert them in database. after inserting 90 books I had 1000 records and I found out that it was wrong. Now, I create a table of content and I insert all content of every books(every book has a record), so I want to split content with character(*).
but it doesn't work.
It is my Previous code:
$sql2 = "SELECT tblcontent.content
from tblcontent,tblstory
where tblcontent.storyid=tblstory.storyid
and tblcontent.storyid='$storyid'";
$r2 = #mysqli_query($dbLink,$sql2);
$result2 = array();
while($res2 = #mysqli_fetch_assoc($r2))
{
$result2[] = $res2;
}
and I've added this code:
$result2=explode("*",$result2);
and
if(isset($result2)){
echo json_encode(array("result2"=>$result2));
}
But it doesn't work.Thanks in advance

Related

Dynamic generation of unordered list from database with PHP and SQL

I've started to code in April 2021 so I'm super new to this. Working on my final exam, I'd need your precious help! I want to generate a dynamic list from a database, containing 2 joined tables (users and interest). The 2 tables both contain "ID_user" which links them as a foreign key. The idea is that one the user is logged in, the profile page displays all the interests the user selected at sign up. At the moment I can only display the last interest selected and not all of them.
Here is my php:
$request2 = "SELECT `interest`.`name_Interest`
FROM `interest`
INNER JOIN `users`
ON `interest`.`ID_user` = `users`.`ID_user`
WHERE `pseudo` = '".$url_pseudo."'
";
$resultat2 = mysqli_query($connexion, $request2) or die (mysqli_error($connexion));
$nb_resultat2 = mysqli_num_rows($resultat2);
if ($nb_resultat2 > 0) {
while ($row = mysqli_fetch_array($resultat2)){
$name_Interest = $row["name_Interest"];
}
}
Here is the HTML displaying the response:
enter image description here
Here is my db:
enter image description here
Any idea why I can get only 1 value?
enter image description here
thanks in advance
Your while loop is writing to the same variable for each iteration of the loop;
while ($row = mysqli_fetch_array($resultat2)){
$name_Interest = $row["name_Interest"];
}
This will leave $name_Interest containing the last value from your database after the loop has completed.
To resolve this, you will need to keep a list of interest names - this can be achieved by using an array. PHP Array Documentation
// Declares the empty array
$interests = [];
// Loop through database results
while ($row = mysqli_fetch_array($resultat2)){
// Add this value to the array
$interests[] = $row["name_Interest"];
}
Now, $interests will hold all of the values from the database!
You will need to print these out differently in your HTML, by looping through all the values in the array and printing one at a time:
(PHP foreach documentation)
<ul>
<?php foreach ($interests as $interest) { ?>
<li><?php echo $interest; ?></li>
<?php } ?>
</ul>
Solution
Simple store all user interests on array and then show in iteration on page.
Code:
$user_interests=array();
while ($row = mysqli_fetch_array($resultat2)){
$user_interests[] = $row["name_Interest"];
}
Now $user_interests array holds all interests of users as a result of join.
At last loop over it
<?php foreach ($user_interests as $interest) { ?>
<p><?php echo $interest; ?></p>
<?php } ?>

Multiple loops in flat database

http://projects.ourplanet.tk/junetxtdb/
http://code.google.com/p/junetxtdb/ in cms (LekkiCMS)
Now my question is how change this code :
$query = $db->select('wizyty');
foreach($query as $record) {
$idz = $record['pro'];
$query2 = $db->select('wizyty_zabiegi',array('id'=>$idz));
foreach($query2 as $record2) {
$record2['name'];
}
}
Every table has lots of values
table wizyty has organized this way
ID"PID"pro"date"time"value1"value2
1"1"2"2020-12-30"12:00"1"2
2"1"1"2020-05-30"12:00"1"2
and table wizyty_zabiegi this way
ID"name"TIMES"HOW
1"Masaż stóp"25"100
2"Masaż nóg"25"100
i use even for (valuepro = valueid)
but this show only good in first result
third, five , six etc result dont show correctly
thank you ;)
i know in mysql i have join but in this project i dont have it ;(
i wrote this question and i found solution hahah
$is= $record['zabieg'] -1;
$query2 = $db->select('wizyty_zabiegi');
$result .= $query2[$is]['nazwa'];
thanks for everything even for reading this messages

Passing multiple checkbox values to different columns of database

I am pretty new to PHP, but have tried searching for other questions similar to mine and been unable to find anything that is close enough to my situation to help me solve this.
I am trying to code a web page that allows users to select as many or as few items as they would like to order. The item values are identical to their Primary Key in the Item table.
Once submitted, each different item value should be input into the same row of a database table based on the date{pk}. Within that row, there are numerous columns: Item1ID, Item2ID, Item3ID, etc.
So far, the value of each item selected is assigned to a new array. However, I cannot simply input the array values into a column -- I need each array index to be placed into a sequential column. The code is below:
$date = new DateTime();
$td = $date->format('Y-m-d');
$x = 1;
$checkedItems = $_POST['Item'];
$count = count($checkedItems);
echo $count;
$foodID = "Item".$x."ID";
While($x<=$count){
if(isset($_POST['Item'])){
if (is_array($_POST['Item'])) {
foreach($_POST['Item'] as $values){
$selectedFoods = substr($values,0,4);
$addFoodOrderQuery= sprintf("UPDATE WeeklyBasketFoodOrder SET '%s' = %s WHERE `foodOrderDate` = '%s'",
$foodID, $selectedFoods, $td);
$result= mysqli_query($db, $addFoodOrderQuery);
}
}
} else {
$values = $_POST['Item'];
echo "You have not selected any items to order.";
}
$x++;
}
If you need any further clarification, please let me know. After submitting the code, the database item#ID tables are different, but they are now empty instead of "NULL."

Displaying data from 3 arrays with correct format

Hello and thanks in advance to anyone that can answer my question. I'm still a bit green in terms of PHP but I will try to explain what I want and what my problem is.
I have 3 arrays with MySQL query's results:
$resultsTextPageID (with pageID value [int(10)])
$resultsTextPageName (with pageName value [text])
$resultsTextIntro (with pageIntro value [text])
I would like the final output to be
<b>[pageName goes here]</b><br />
[pageIntro goes here]<br /><br />
Like this:
[pageName]
[pageIntro]
[pageName]
[pageIntro]
I tried the following code:
//ECHO PAGEID PART
while ($pageID = mysql_fetch_assoc($resultsTextPageID))
{
echo '<b><a href="page.php?id='.$pageID['pageID'].'">';
//ECHO PAGENAME PART
while ($pageName = mysql_fetch_assoc($resultsTextPageName))
{
echo $pageName['pageName'].'</a></b><br />';
//ECHO PAGEINTRO PART
while ($intro = mysql_fetch_assoc($resultsTextIntro))
{
echo $intro['pageIntro'].'<br /><br />';
}
}
}
But the output I get is:
[pageName]
[pageIntro]
[pageIntro]
[pageName]
I think the problem is on the way I structured the while loops, but for the life of me, I can't figure out how to fix it.
Can someone help me? Again, thanks in advance! :D
EDIT 1:
Here is the query code:
//Prepare and set search query string
$q = preg_replace("/[^a-zA-Z0-9 !?.:]+/", " ", $_GET['q']);
//RETRIEVE KEYWORDS
//seperate multiple keywords into array
$keywords = explode(" ", $q);
//Clean empty arrays so they don’t get every row as result
$keywords = array_diff($keywords, array(""));
//MySQL QUERY
$searchTextPageID = "SELECT pageID FROM pages WHERE pageIntro LIKE '%".$keywords[$i]."%' OR pageText LIKE '%".$keywords[$i]."%'";
$searchTextPageName = "SELECT pageName FROM pages WHERE pageIntro LIKE '%".$keywords[$i]."%' OR pageText LIKE '%".$keywords[$i]."%'";
$searchTextIntro = "SELECT pageIntro FROM pages WHERE pageIntro LIKE '%".$keywords[$i]."%' OR pageText LIKE '%".$keywords[$i]."%'";
Essentilally you should be collecting all 3 pieces of info at one time, if these are all in the same table, the job is quite easy.
$qry = "select pageID, pageName, pageIntro from <your table name>";
// now loop thru results
while ($page = mysql_fetch_assoc($qry))
{
echo '<b><a href="page.php?id='.$page['pageID'].'">';
echo $page['pageName'].'</a></b><p>';
echo $page['pageIntro'].'<br /></p>';
}
If the data is spread over more than one table you will have to do a JOIN in your sql.
Your code doesn´t make much sense since you iterate over every entry of $resultsTextPageID but already in the first entry you iterate over all $resultsTextPageName. Therefore the second time you enter the body of resultsTextPageID-loop there is no more to fetch from $resultsTextPageName. This happens the exact same way to the second/third while-loop.
Assuming you have only one title and only one page intro you can change your code to
while ($pageID = mysql_fetch_assoc($resultsTextPageID))
{
/* get only ONE entry */
$pageName = mysql_fetch_assoc($resultsTextPageName);
$intro = mysql_fetch_assoc($resultsTextIntro);
echo '<b><a href="page.php?id='.$pageID['pageID'].'">';
echo $pageName['pageName'].'</a></b><br />';
echo $intro['pageIntro'].'<br /><br />';
}
But that is in no way nice code.
You should take a look at mysql JOIN commands to arrange your data correctly in the database select. Then your output code would be much easier.
EDIT because you added mysql-code:
you are selecting 3 times from the same db under the same condition, only to retrieve different columns, change it to
$searchTextPageID = "SELECT pageIDm, pageName, pageIntro FROM pages WHERE pageIntro LIKE '%".$keywords[$i]."%' OR pageText LIKE '%".$keywords[$i]."%'";

Comparing a php variable and mysql table element that has backslashes

I'm trying to create an online database of the music I locally have on my computer. I already have a table of every song in my library and would like to create a different table with just the song ID's (auto-incremented when I added the songs to my main table) that act as one of my playlists.
From what I can tell, the only 100% certifiable method for matching the songs is by the location on my disk ( C:\Users\username\Music\iTunes\iTunes Media\Music\Jonathan Coulton and GLaDOS\Portal\128 128 Still Alive Duet.mp3 ) as an example. In my PHP code I get the song location into a variable and if I print it relative to the equivalent song location in my MYSql table, they match up exactly but when I try to run a select statement using that, it gives me an error. From what I can tell this is being caused by the backslashes in the location info.
This is the select statement I'm using,
SELECT id FROM itunes WHERE Location=$locationval
where $locationval is the current song's location, id is the autoincremented id in my main table, and itunes is my main table.
Is there any way around this? And as I am a beginner, is the backslashes really the issue?
For reference here is the full code for importing the playlist, its using the DB plugin for PEAR (a PHP extension).
<?php
// define table name
define('TABLE_NAME', 'playlist');
// create database connection
require_once('DB.php');
$dsn = 'mysql://username:password#localhost/itunes';
$DB =& DB::connect($dsn);
if (DB::isError($DB)) {
die($DB->getMessage());
}
$DB->setFetchMode(DB_FETCHMODE_ASSOC);
// load text file
$file = file_get_contents('Portal.txt');
// explode on new line
$file = explode("\r", $file);
set_time_limit(0);
// loop through each line in the file
foreach ($file as $key => $value) {
// explode on tab to get column list
$exploded = explode("\t", $value);
// check for first row, which contains column headers
if ($key == 0) {
}
else{
if(count($exploded)>3)
{
$locationval=$exploded[26];
echo $exploded[26];
echo "<br />";
$result = mysql_query("SELECT id FROM itunes WHERE Location=$locationval");
//$result = mysql_query("SELECT * FROM itunes WHERE id=8292");
set_time_limit(0);
$row = mysql_fetch_row($result);
//test statements to see if the query worked
echo "Test: ";
echo $row['id'];
echo $row['Location'];
echo "<br />";
}
}
}
?>
Which was modified from the code here: http://ericlondon.com/posts/208-exporting-itunes-data-into-mysql-and-creating-sql-to-show-top-rated-albums
If any more info is needed, please let me know.
You need to escape the backslashes when using it in mysql as a string literal, so just replace your following line:
$result = mysql_query("SELECT id FROM itunes WHERE Location=$locationval");
for this one:
$result = mysql_query("SELECT id FROM itunes WHERE Location='". str_replace('\\','\\\\',$locationval) . "'");
that should do what you want.

Categories