fetch data from array is very slow while display - php

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.

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);?>

Use HTML Form to Update SQL Data

I'm looking for help with my products list.
My Code:
<!DOCTYPE html>
<html>
<head>
<title> Produktliste </title>
</head>
<body>
<iframe name="dir" style="display:none;"></iframe>
<form action="shop.php" method="post">
<p> <h2> Produkt hinzufügen </h2> </p>
<p> Produktname: <input type="text" name="Produktname"/> </p>
<p> Produktbeschreibung: <textarea rows=2 cols=20 name="Produktbeschreibung"></textarea> </p>
<p> Preis: <input type="text" name="Preis"/> </p>
<input type="submit" name="speichern" value="Speichern"/>
</form>
<?php
$connect = new mysqli ('localhost', 'root', '');
$connect->select_db('shop');
if (#$_REQUEST["Produktname"] && #$_REQUEST["Produktbeschreibung"] && #$_REQUEST["Preis"]) {
$produktname = #$_REQUEST["Produktname"];
$beschreibung = #$_REQUEST["Produktbeschreibung"];
$preis = #$_REQUEST["Preis"];
$result = $connect->query("INSERT INTO `shop`.`produkte` (`Produktname`, `Beschreibung`, `Preis`) VALUES ('$produktname', '$beschreibung', '$preis');");
if(!$result) {
echo "SQL Fehler: " . $connect->error;
die;
} else { echo "Letzte ID: " . $connect->insert_id;
}
}
?>
<table border="2" width="30%" style="border:1px solid #000000; border-spacing:inherit; text-align:left;">
<br><br>
<tr>
<td> Produkt </td>
<td> Beschreibung </td>
<td> Preis </td>
<td> Funktionen </td>
<?php
$result = $connect->query("SELECT * FROM produkte");
while($obj = $result->fetch_object()) {
echo '<tr><td>' . $obj->Produktname . '</td><td>' . $obj->Beschreibung . '</td><td>' . $obj->Preis . ' EUR ' . '</td><td> Bearbeiten, Löschen </td></tr>';
}
?>
</tr>
</table>
<?php
if (isset($_REQUEST["delete"])) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlpart = explode('=', $url);
$ProduktID = end($urlpart);
$result = $connect->query("DELETE FROM `shop`.`produkte` WHERE `ProduktID` = $ProduktID;");
header('Location: ./shop.php');
}
if(isset($_REQUEST["id"])) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlpart = explode('=', $url);
$ProduktID = end($urlpart);
// Update SQL Data?
}
if (!$result) {
echo "SQL Fehler: " . $connect->error;
die;
}
?>
</body>
</html>
I'm now looking for a way to retrieve the MySQL Data with the equivalent ID into the existing HTML Form and update it back to the MySQL Database... I'm currently learning PHP at the University and I can't think any further by myself.
It needs to get done withing this PHP File, like everything else is.
Thanks for any help! :)
If I understand you correct, you want to echo inserted row from database. Change the line:
$result = $connect->query("SELECT * FROM produkte");
into:
$result = $connect->query("SELECT * FROM produkte WHERE ID_prod_column = '$insertID'");
Try something like this. Just change "ID_prod_column" to correct name and $insertID to correct variable.

Drop down, results table not showing Mysql php

Trying to get the results from the Mysql to show up on the web page.
The process is that the user would select a make of a car and then it will show just that make in a table.
I've been trying different things but I cant seem to get it to show the results. As soon as I get rid of the WHERE statement in the sql query it shows all the cars/makes. I think the problem is in the sql statement or the if.
This is what I've got so far.
<HTML >
<head>
<title>Inventory</title>
</head>
<body>
<form method="get" action="TaskC.php">
Please select a make:
<select name = "make" >
<option value = "All">All</option>
<option value = "Toyota">Toyota</option>
<option value = "Holden">Holden</option>
<option value = "Ford">Ford</option>
<option value = "Nissan">Nissan</option>
</select> <br/>
<br/>
<input type="submit" value="Search" name="Search" />
<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th>Make</th>
<th>Model</th>
<th>Price</th>
<th>Quantity</th>
<tr>
</form>
<?php
//error_reporting (E_ALL ^ E_NOTICE);
$dbConnect = mysqli_connect('xxxxxxxxx', 'xxxxxxxxx','xxxxxxxx')
or die("<p>The database server is not available.</p>");
$dbSelect = mysqli_select_db( $dbConnect,'xxxxxxxx_db' )
or die("<p>The database is not available.</p>");
$make = $_GET['make'];
$sqli = "SELECT * FROM inventory WHERE make = '" .$make. "'";
$result = mysqli_query($dbConnect,$sqli);
if (isset($_GET['make']) )
{
while ($inventory = mysqli_fetch_assoc($result) )
{
echo "<tr>";
echo "<td>".$inventory['make']."</td>";
echo "<td>".$inventory['model']."</td>";
echo "<td>".$inventory['price']."</td>";
echo "<td>".$inventory['quantity']."</td>";
echo "</tr>";
}
}
mysqli_close($dbConnect);
?>
</body>
</HTML>
Hope you can help.
Thanks
There is an error in the query. It should be -
$sqli = "SELECT * FROM inventory WHERE make = '" .$make. "'";
Edit
if (isset($_GET['make']) ){
$make = $_GET['make'];
$sqli = "SELECT * FROM inventory WHERE make = '" .$make. "'";
$result = mysqli_query($dbConnect,$sqli);
while ($inventory = mysqli_fetch_assoc($result) )
{
echo "<tr>";
echo "<td>".$inventory['make']."</td>";
echo "<td>".$inventory['model']."</td>";
echo "<td>".$inventory['price']."</td>";
echo "<td>".$inventory['quantity']."</td>";
echo "</tr>";
}
}

Pass PHP array through Select Option Fields

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 ;-)

How to delete from my database in PHP/mysql?

Hi there I have many implementations of some php files. All of which have some errors. I will start off with an apology as this is my first question on here and I am certain that I will do this incorrectly as I see many first timers do. I will give as much info as possible and make it relevant to as many people as possible.
I have a database and am having trouble deleting from it. The database is simple. It includes resource_id name room description time_available and uer_id.
Although I expect it to output name description and resources_id it only outputs name and description and it will not let me delete name by resources_id.
How to delete from my database in PHP/mysql?
This is my delete_resources.php
{
<html>
<head>
<title>Delete a Record from MySQL Database</title>
</head>
<body>
<?php
$db_host = "#######";
// Place the username for the MySQL database here
$db_username = "#######";
// Place the password for the MySQL database here
$db_pass = "#######";
// Place the name for the MySQL database here
$db_name = "#######";
//
$con = mysqli_connect("$db_host","$db_username","$db_pass","$db_name");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
mysqli_close($con);
}
$result = mysqli_query($con, "SELECT * FROM resources");
echo 'name' . "\t" . 'description' . "\t" . 'resources_id';
echo "<br>";
while($row = mysqli_fetch_array($result))
{
echo $row['name'] . "\t" . $row['description'] . "\t" . $row['resources_id'];
echo "<br>";
}
// Echoes: string
echo gettype($array);
//
if(isset($_POST['delete']))
{
// Query to select an int column
$resources_id = $_POST['resources_id'];
$sql = "DELETE name From resources ".
"WHERE resources_id = $resources_id" ;
//mysql_select_db('b32_13993766_csc411');
//$retval = mysql_query( $sql, $conn );
if(! $result )
{
die('Could not delete data: ' . mysql_error());
}
else if( $result )
{
echo "Deleted data successfully\n";
}
//mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Resource ID</td>
<td><input name="resources_id" type="text" id="resources_id"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="delete" type="submit" id="delete" value="Delete">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
//
}
You are not executing that delete query. Should look like
$recources_id=intval($resources_id);
$sql = "DELETE FROM resources WHERE resources_id = $resources_id" ;
$result = mysqli_query($con, $sql); // This is missing
$sql_query="Delete from your_table_name where id ='".$your_id."'";
$sql = "DELETE FROM resources WHERE resources_id = $resources_id" ;
Your $result is not relevant at all with your delete query (it is referring to the $result above, not the one with the delete). Try changing to this and see if it works.
if(isset($_POST['delete']))
{
// Query to select an int column
$resources_id = $_POST['resources_id'];
$sql = "DELETE name From resources ".
"WHERE resources_id = $resources_id" ;
$result = mysqli_query($con, $sql); //add this line
//mysql_select_db('b32_13993766_csc411');
//$retval = mysql_query( $sql, $conn );
if(! $result )
{
die('Could not delete data: ' . mysql_error());
}
else if( $result )
{
echo "Deleted data successfully\n";
}
//mysql_close($conn);
}

Categories