Pass PHP array through Select Option Fields - php

I am writing a basic CMS system and have come across something which should be seemingly simple -but is beginning to frustrate me.!
I am trying to pass an array through a select option field to populate a list of categories in which I can save a post.
I have a 'posts' form which comprises of 3 fields. Title, content and Category ID (CatID).
When the user creates a post, they can select the category they wish to assign the post assigned to by using a drop down list - (this is populated by using a different form).
So the technical bit; -
MySQL DB:-
categories = catname (char60 PRIMARY), catid (INT10, AI)
posts = id (bigint20 PRIMARY), catid (int10 PRIMARY), title (text), content (varchar255)
Example of categories populates: catname = Home / catid = 1 ...etc
Output.php ;
<?php
function display_post_form($post = '') {
$edit = is_array($post);
?>
<form action="<?php echo $edit ? 'edit.php' : 'add.php' ; ?>" method="post">
<table border="0">
<tr>
<td> Title:</td>
<td> <input type="text" name="title" value="<?php echo $edit ? $post['title'] : '' ; ?>" size="60" /> </td>
</tr><tr>
<td> Content:</td>
<td> <textarea id="editor1" name="content" value="<?php echo $edit ? $post['content'] : '' ; ?>"> </textarea> </td>
</tr><tr>
<td> Category:</td>
<td><select name="catid">
<?php
$cat_array = get_categories($catid, $catname);
foreach($cat_array as $thiscat) {
echo "<option value=\"".$thiscat['catid']."\" ";
if (($edit) && ($thiscat['catid'] == $post['catid'])) {
echo " selected";
}
echo ">".$thiscat['catname']."</option>";
}
?>
</select>
</td>
</tr><tr>
<td> Button:</td>
<td <?php if (!$edit) { echo "colspan=2"; } ?> align="center">
<?php
if ($edit)
echo "<input type=\"hidden\" name=\"_id\" value=\"". $post['id'] ."\" />";
?>
<input type="submit" value="<?php echo $edit ? 'Update' : 'Add' ; ?> Post" />
</form></td>
</td>
</tr>
</table>
</form>
<?php
}
?>
Functions.php ;
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
while($row = mysqli_fetch_assoc($result)) {
printf("\n %s %s |\n",$row["catname"],$row["catid"]);
}
mysqli_close($conn);
}
I am able to call in the 'get_cattegories()' function which generates a flat data of categories and their respective id's. I then combined this with the Select Option Field in the Output.php file and it doesn't generate anything.
Can anyone give some useful tips or advice? Many thanks :)

You are not returning the array but printing a string to the output. Change printf to return:
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
$categories = array();
while($row = mysqli_fetch_assoc($result)) {
$categories[] = $row;
}
mysqli_close($conn);
return $categories;
}
Also I agree for the comments to your question. The arguments are useless.
You also may refactor the code, actually... alot. Move the mysql_connect() to the other place, probably at the beginning of your script.
I suggest to use some frameworks. I think KohanaPHP will be a good start. You will learn about architecture and some design patterns. Keep the good work and improve your skills ;-)

Related

how to insert multidimensional array using for loop

I have 2 tables. One is for students and one of subjects. I want to fetch data from the students and subjects tables on same page. In front of student 1 subject 1 subject 2 subject 3. Then in front of student 2 subject 1 subject 2 subject 3. It is to submit result.
I have done this.
Than I have to insert this in 3rd table of results. I have successfully inserted students in result table. And subjects. But on the time of marks, I am unable to insert. I used a multidimensional array. I am unable to insert marks data into array. How can I do this?
Let me show some snapshots.
My multidimensional array is not working, and I don't know how to do this. Kindly help me out.
This is a detailed pic: This is the detailed snapshot.
// count students
$sql = "SELECT * FROM tb_students";
$run = mysqli_query($mysqli,$sql);
$total_students = mysqli_num_rows($run);
$numbers=$total_students;
for($i=1;$i<=$numbers;$i++)
{
while ($rows = mysqli_fetch_assoc($run)) {
$id = $rows['student_id'];
$name = $rows['student_name'];
?>
<tr>
<td>Name</td>
<td hidden><input type="text" value="<?php echo $id?>" name="student_id[]" /></td>
<td><?php echo $name ?> </td>
</tr>
<input type="hidden" value="<?php echo $numbers;?>" name="numbers" />
<?php
$sel_sub = "SELECT * FROM subjects WHERE class_name = '1st year'";
$run_sub = mysqli_query($mysqli,$sel_sub);
$total_sub = mysqli_num_rows($run_sub);
for ($k=0; $k < $total_sub ; $k++) {
while ($rows = mysqli_fetch_assoc($run_sub)) {
$sub_id = $rows['sub_id'];
$sub_name = $rows['sub_name'];
?>
<tr>
<td><?php echo $sub_name; ?></td>
<td hidden><input type="" value="<?php echo $sub_id;?>" name="sub_id[]" /></td>
<input type="hidden" value="<?php echo $total_sub;?>" name="subject" />
<td><input type="text" name="marks[][]" placeholder="Marks" /></td>
</tr>
<?php
}
}
?>`
and this is isnert query
<?php
$mysqli = mysqli_connect("localhost","salman","salman1214","shan");
if(mysqli_connect_errno())
die("Connection failed".mysqli_connect_error());
$s = '';
for($i=0;$i<$_POST['numbers'];$i++)
{
for($j=0;$j<$_POST['subject'];$j++)
{
$s = "insert into result(student_id,exam_name, subject_name, sub_marks) values";
$s .="('".$_POST['student_id'][$i]."','".$_POST['exam_name']."','".$_POST['sub_id'][$j]."','".$_POST['marks'][$i][$j]."'),";
$s = rtrim($s,",");
if(!mysqli_query($mysqli,$s))
echo mysqli_error();
else
echo "Records Saved <br />";
$sub_list = $_POST['marks'][$i][$j];
echo $sub_list;
}
}
mysqli_close($mysqli);?>
I don't want to say if this way is the best way.
But, your problem is you are using the lines in the loops which should not. Try this:
<?php
$mysqli = mysqli_connect("localhost","salman","salman1214","shan");
if(mysqli_connect_errno())
die("Connection failed".mysqli_connect_error());
$s = '';
$s = "insert into result(student_id,exam_name, subject_name, sub_marks) values";
for($i=0;$i<$_POST['numbers'];$i++)
{
for($j=0;$j<$_POST['subject'];$j++)
{
$s .="('".$_POST['student_id'][$i]."','".$_POST['exam_name']."','".$_POST['sub_id'][$j]."','".$_POST['marks'][$i][$j]."'),";
}
}
$s = rtrim($s,",");
if(!mysqli_query($mysqli,$s))
echo mysqli_error();
else
echo "Records Saved <br />";
mysqli_close($mysqli);?>

PHP/SQL - How can I get the name of tables in my database?

I am trying to use the function mysqli_fetch_field() to get the name of each of my tables in the database. However when i try to output the table name using $fieldInfo->table i get duplicates. How can i select only 1 column from each table so that $fieldInfo->table isnt called for every column of each table?
current sql:
$sql = "SELECT * from administrators, bookings, customers, rooms";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
my code to display the table name in radio buttons:
<?php
while ($fieldInfo = mysqli_fetch_field($results)) {
?>
<input type="radio" name="tableNames" value="<?php echo $fieldInfo->table; ?>"> <?php echo $fieldInfo->table ?> <br>
<?php } ?>
I added 2 temporary table name holder and made an IF condition that only outputs the radio buttons once the 2 temporary name holders are different.
<?php
$tempName2 = "";
while ($fieldInfo = mysqli_fetch_field($results)) {
$tempName = $fieldInfo->table;
if ($tempName != $tempName2) {
$tempName2 = $tempName;
?>
<input type="radio" name="tableNames" value="<?php echo $tempName; ?>" > <?php echo $tempName ?> <br>
<?php }
} ?>
<?php
$query='SHOW TABLES FROM DB_NAME';
$results=mysqli_query($conn,$query);
while ($fieldInfo = mysqli_fetch_array($results)) { ?>
<input type="radio" name="tableNames" value="<?php echo $fieldInfo[0]; ?>"> <?php echo $fieldInfo[0]; ?> <br>
<?php } ?>

Adding new record to database prevents echoing other records

Hi i have created a forum website where logged in users can create topics using a form on each forum topic, however when I add a new record using the form it prevents itself and the previous topics from being displayed.
I have no idea why and would be greatful for any help.
I have my forum page which displays categories, topics(if category is selected) and replies (if topic is selected). Here is the code for my forum.php page
<div id="midclmn">
<?php
If (isset($_GET['topic'])){
// Show topic & replies
$queryreply = "SELECT a.reply_id,a.reply_text, a.reply_date, b.topic_title, b.topic_date,c.username AS reply_user, (SELECT username FROM users
WHERE user_id=b.user_id) AS topic_creator FROM forum_replies a
LEFT JOIN forum_topics b ON a.topic_id=b.topic_id
LEFT JOIN users c ON a.user_id=c.user_id
WHERE a.topic_id = '".$_GET['topic']."' ";
$result = mysql_query($queryreply) or die (mysql_error());
$row = mysql_fetch_array($result);
if(empty($row['reply_id'])){
echo "No replies have been posted in this Topic, be the first to have your say using form below.";} ?>
<table id="categorytable">
<tr><td><?php echo '<b>'.$row['topic_title'].'</b>';?></b><br></td></tr>
<tr><td><?php echo 'Topic published by '.$row['topic_creator'].' - ( '.$row['topic_date'].' )'.'';?><br><br></td></tr>
<tr><td><?php $row['reply_user'].' Replied with: ';?><br></td></tr>
<tr><td><?php echo $row['reply_text'].'<br><br><i>Published: '.$row['reply_date'].' by '.$row['reply_user'].'</i>';?></td></tr>
<?php
while ($row = mysql_fetch_array($result)){ ?>
<tr><td><?php $row['reply_user'].' Replied with: ';?><br></td></tr>
<tr><td><?php echo $row['reply_text'].'<br><br><i>Published: '.$row['reply_date'].' by '.$row['reply_user'].'</i>';?></td></tr>
<?php
}
?>
</table>
<?php
}elseif (isset($_GET['cat'])){
// Show topics in that category
$querytopic = "SELECT topic_id, topic_title,topic_description, topic_date, category_id FROM forum_topics WHERE category_id = '".$_GET['cat']."'";
$result = mysql_query($querytopic) or die (mysql_error());
$row = mysql_fetch_array($result);
if(empty($row['topic_id'])){
echo "No topics have been posted in this category, be the first to submit a topic using form below."; ?>
<table id="categorytable">
<tr><td><?php echo '<b>'.$row['topic_title'].'</b>';?></td></tr>
<tr><td><?php echo $row['topic_description'];?><br><br></td></tr>
<tr><td><?php echo "<b>Date Posted:</b> ".$row['topic_date'];?><br><br></td></tr>
<?php
while ($row = mysql_fetch_array($result)){ ?>
<tr><td><?php echo '<br>'.$row['topic_title'].'</b>';?></td></tr>
<tr><td><?php echo $row['topic_description'];?><br><br></td></tr>
<tr><td><?php echo "<b>Date Posted:</b> ".$row['topic_date'];?><br><br></td></tr>
<?php
}} ?></table><?php
if($_SESSION['loggedin'] === true){
$userid = $_SESSION['id'];
$catid = $_GET['cat'];
?>
<br>
<form method="post" action="topic_process.php" id="topicform">
<h3>Add New Topic</h3>
<input type="hidden" id="catid" name="catid" value=<?php echo $catid?> >
<input type="hidden" id="userid" name="userid" value=<?php echo $userid ?>>
<label for="topictitle">Topic Title: </label>
<textarea rows="2" cols="80" id="topictitle" name="topictitle" required ></textarea>
<br><br>
<label for="topicdescription">Topic Description: </label>
<textarea rows="10" cols="80" id="topicdescription" name="topicdescription" required ></textarea>
<input type= "hidden" id="topicdate" name="topicdate" value=<?php echo ''.date('Y-m-d').'' ?>>
<br><br>
<input type="submit" name="topicsubmit" id="topicsubmit" value="Create Topic">
</form>
<?php
}
?>
<?php
}else{
//Just display the list of categories
$querycategory = "SELECT category_id, category_title,category_description FROM forum_category";
$result = mysql_query($querycategory) or die (mysql_error());
$row = mysql_fetch_array($result); ?>
<table id="categorytable">
<tr><td><?php echo ''.$row['category_title'].'';?></td></tr>
<tr><td><?php echo $row['category_description'];?><br><br></td></tr>
<?php
while ($row = mysql_fetch_array($result)){ ?>
<tr><td><?php echo ''.$row['category_title'].'';?></td></tr>
<tr><td><?php echo $row['category_description'];?><br><br></td></tr>
<?php
}
?>
</table>
<?php }
?>
</div>
and here is the process page
session_start();
include "includes/connection.php";
echo $_POST['topictitle'];
echo $_POST['topicdescription'];
echo $_POST['userid'];
echo $_POST['catid'];
$query = "INSERT INTO forum_topics
(
category_id,
user_id,
topic_title,
topic_description,
topic_date
)
VALUES
(
'".$_POST['catid']."',
'".$_POST['userid']."',
'".$_POST['topictitle']."',
'".$_POST['topicdescription']."',
'".$_POST['topicdate']."'
)";
mysql_query($query) or die (mysql_error());
header('Location: /TEST/forum.php?'.$_POST['catid'].'');
?>
I am also struggling to record the topic_date as today's date I tried date('Y-m-d') for 2015-04-28 but it saved as 00-00-00.
I know its a lot of code to read but I'm really stuck and don't want to miss anything, also I know mysql_functions are deprecated but have been asked to use them by uni.
Im using PHPmyadmin as the database, which I know is rubbish!
Thanks
EDIT: I have set up the page so It displays all the topics stored in the database (topic_title, topic_description, user_id, topic_date). before I add a new topic to the database this works fine but afterwards all the topics including the new one disappear leaving just the form on the page. All the records still exist on the database and deleting the new record brings back all the topics displayed on the page.

fetch data from array is very slow while display

This is my code:
<?php
if(isset($_POST['submit']) & !empty($_POST['appid'])) {
$app = mysql_real_escape_string($_POST['appid']);
//database parameters
$conp = mysqli_connect($hostname, $user, $password, $database) or die('error in connection' . mysqli_error());
//actual data for appid's
$appsi = mysqli_query($conp, "SELECT distinct package_name FROM `user_app` where `app_id` = '$app'");
$all = array();
while($row = mysqli_fetch_assoc($appsi)) {
$all[] = $row["package_name"]; // array problem
}
foreach ($all as $value) {
$install = mysqli_query($conp, "SELECT COUNT(*) AS installs from `install` where package_name = '$value'");
$row = mysqli_fetch_assoc($install);
$data[] = '<b>' .$row["installs"] . '</b>';
$reg = mysqli_query($conp, "SELECT COUNT( DISTINCT `imei_num` ) AS reg FROM `user_app` WHERE package_name = '$value'");
$row = mysqli_fetch_assoc($reg);
$regd[] = '<b>' .$row["reg"] . '</b>';
}
}
mysqli_close($conp);
?>
<html>
<head>
<title>script</title>
</style>
</head>
<body>
<span style="text-align: center"><h1>Beta</h1></span>
<form name="query" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>Enter Application-Specific Id:</p>
<select name='appid'>
<?php
$conp = mysqli_connect($hostname, $user, $password, $database) or die('error in connection' . mysqli_error());
$getid = mysqli_query($conp, "SELECT distinct `app_id`, `appidt` from `user_app` group by `app_id`") or die('get data failed' . mysqli_error());
while(($row = mysqli_fetch_assoc($getid)) != null) {
echo "<option value = '{$row['app_id']}' selected = 'selected'";
if ($selected == $row['app_id']) {
echo "selected = 'selected'";
}
echo ">{$row['appidt']}</option>";
}
mysqli_close($conp);
?>
</select>
<p><input type="submit" name="submit" value="Go" /></p>
</form>
<div>
<p><?php echo '<br />' .'<b>'. 'Application Id : '. $app . '</b>'; ?> </p>
<hr />
<table border=2px width=100%>
<tr>
<th><b>App Packages</b></th>
<th><b>Registrations</b></th>
<th><b>Installs</b></th>
</tr>
<tr>
<td><?php echo implode("<br><br>", $all); ?></td>
<td align="center"><?php echo implode("<br><br>", $regd); ?></td>
<td align="center"><?php echo implode("<br><br>", $data); ?></td>
</tr>
</table>
<p><?php echo "$name"; ?></p>
</div>
</body>
</html>
I am fetching my all package names in an array: all[], packages might be 10 or 20 in ranges, after this i want all downloads corresponding to packages which is on another table name downloads and packages on another table app_packages.
I can't uses join because package table contain specific packages but downloads contain many number of downloads corresponding to packages.
So, i put all packages in all[] and use them in foreach loop name $value, now i get all installs per packages and i can display it via implode function. But in my frontend, when i select an appid from dropdown as you can see, it will take huge time to retrieve downloads number per packages. This is not what i want to display because it is very time taking.
Please see this problem, and if i missing something in explanation then i apologize, prompt me and i mention it.
Using query in loop is a bad idea. that is the reason you are geting slow result. it touches database on each iteration. you can do this with subquery or join as alternative way.

when I am selecting multiple checkbox for deletion...only last one checkbox is deleted ! means it can delete 1 data from a database

Below code !Gives me check boxes and a delete button, In input tag all check box have same name (check)!! There check box can be retreive from database with id .
Problem Is:: when I am selecting multiple checkbox for deletion...only last one checkbox is deleted ! means it can delete 1 data from a database.
url like -> http://localhost/demo/delete.php?check=10&check=13&check=14&submit=Delete
I need while I am selecting a checkbox more than 1 checkbox ,check box datas is deleted from database ! Any one help me to overcome this problem thanks
index.php
<?php
$sql = mysql_connect('localhost', 'root', '');
mysql_select_db('database_section', $sql);
?>
<form name="checkbox" method="get" action="delete.php">
<table>
<tr>
<?php
$sql = "select * from data";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
?>
<td><input type="checkbox" name="check" value="<?php echo $row['id']?>"><?php echo $row['data'];?>
</td>
<?php
}
?>
<tr>
<td><input type="submit" name="submit" value="Delete"></td>
</tr>
</table>
</form>
Now, In delete.php..code below...
<?php
$sql = mysql_connect('localhost', 'root', '');
mysql_select_db('database_section', $sql);
if ($_REQUEST['submit']) {
$abc = $_GET['check'];
$sql = "Delete from data where id=$abc";
$result = mysql_query($sql) or die(mysql_error());
if (isset($result)) {
echo "data deleted";
}
else
{
echo "not possible";
}
}
?>
Use check box as an array holder. name it as check[] to hold all selected values. And on post you will get the selected array list.
Now your $abc will be a array, use foreach in delete.php to get the checked ids.
Change name="check" to name="check[]"
See more here: http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
[...]
while ($row = mysql_fetch_array($result))
{
?>
<td>
<input type="checkbox" name="check[]" value="<?php echo $row['id']?>"><?php echo $row['data']; ?>
</td>
<?php
}
?>
[...]

Categories