I have been trying to store an array in a database column, but haven't succeeded yet.
I have been looking into php and sql for two weeks now, and I don't have a programming background. So please forgive my ignorance. I'm sure I've made lot's of mistakes.
Let me explain my situation further.
I created a web page so a admin can fill in some data concerning some game. This is after a login process.
When a admin arrives at this point, I'm not bothering with 'correct' input at the moment. I just want to get the data in the db.
I created a table called games with mysql, and filled it with data I have so far:
+--------+--------+-----+-----+------+------+------+
|game_id |round_id|team1|team2|score1|score2|result|
+--------+--------+-----+-----+------+------+------+
| 1 | 1 | A | B | NULL | NULL | NULL |
| 2 | 1 | C | D | NULL | NULL | NULL |
| 3 | 1 | E | F | NULL | NULL | NULL |
| 4 | 2 | E | C | NULL | NULL | NULL |
| 5 | 2 | A | D | NULL | NULL | NULL |
| 6 | 2 | F | B | NULL | NULL | NULL |
+--------+--------+-----+-----+------+------+------+
Then I created a form in a php page which uses data from this table to display the teams per game.
The admin uses this form to fill in the game score and results. See the form below.This form is also needed to store values in the above table.
input.php
<?php
mysql_connect("xxx", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$query="SELECT games_team1, games_team2 FROM games WHERE round_id = 1";
$result = mysql_query($query);
?>
<form action="someform.php" method="post">
<table id="inputgameresults">
<tbody>
<tr>
<th>Home</th>
<th>Score 1</th>
<th>-</th>
<th>Score 2</th>
<th>Away</th>
<th>Result</th>
</tr>
<?php while($row = mysql_fetch_array($result)) { ?>
<tr>
<td><?php echo $row['team1']; ?></td>
<td><input type="text" name="score1[]"/></td>
<td> - </td>
<td><input type="text" name="score2[]"/></td>
<td><?php echo $row['team2']; ?></td>
<td><input type="text" name="result[]"/></td>
</tr>
<?php } ?>
<tr>
<td></td>
<td</td>
<td</td>
<td</td>
<td</td>
<td><input type="submit" value="Submit"/></td>
</tr>
</tbody>
</table>
</form>
This results into 3 rows in the table in the form above. This table displays the teams for each match and input fields for the scores and the result.
A header, three rows with the games, input fields behind the games, and a sumbit button below.
A admin can submit the input with the form below. I added the echo so I can check if the output is correct. The echo works like a charm.
This is where things don't go the way I'd like them to go. The sql query I used is stated in the form. It fails miserably, probably because of my lack of knowledge.
form1.php
<?php
mysql_connect("xxx", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$sc1 = $_POST['score1'];
$sc2 = $_POST['score2'];
$res = $_POST['result'];
foreach($sc1 as $value) {
echo "score team 1 $value<br/>";
mysql_query("UPDATE games SET game_score1 = '".$value[]"' WHERE games_id = [1,2,3] ");
}
foreach($sc2 as $value) {
echo "score team 2$value<br/>";
}
foreach($res as $value) {
echo "res $value<br/>";
}
?>
I'm sure there are a lot things besides the main issue I can improve, or do more efficient. Although this is not my main focus at the moment, any help is welcome :D
The main focus now is to get the input from the form in the right place in the db. The data from the form needs to be send to the database in columns score1, score2 and result for a game.
Any help or advice is most welcome!
a simple way to store a whole array in a database column is to encode the array to json ... in the example, $sc1 is the array you want to store
mysql_query("UPDATE games SET game_score1 = '". json_encode($sc1) . "' WHERE
games_id = [1,2,3,4,5,6,7,8,9] ");
then when you get your array from the colomnu, it is still on json format, so you need to do this
$array = json_decode($result);
sometimes your array contains elemens with '' all you need to do is to use
addslashes(json_encode($sc1))
instead of using
json_encode($sc1);
It looks like you just need the syntax to insert a new row to mysql. If game_id increments automatically, you don't have to specify it in the statment:
INSERT games (round_id, team1, team2, score1, score2, result)
VALUES (3, 4, 6, 18, 1, 0, 1);
In advance, thank you guys for the possible solutions to my problem. I'm definately gonna look into them.
A friend of mine told me that I should use a 'key' so that it would be able to loop in the database. Kinda like when the data was retreived from the database. This seemed to work.
I used a $key++ so it would start at the first games_id.
foreach($sc1 as $key => $value) {
$key++;
mysql_query("UPDATE games SET game_score1 = '".$value[]"' WHERE games_id = '".$key."' ");
}
My next challenge is to retreive per round_id and also store per round_id.
And to make it more interesting, the current date is gonna point to the current round_id :D
Related
I have managed to create a login form which GETS user data from database and displays user data, but i would now like to display the table_name to which that user is related to.
The thing is i will have to use an JOIN because it needs to query the data from 2 tables.
My Problem
I keep getting an error, im not sure if my query in my php file has the wrong syntax and if my method is just the wrong approach.
Connection
Keep in mind my database connections ($db) works perfectly as the user can already log in with username and password
Error
Notice: Undefined variable: rows in C:\xampp\htdocs\score4score\table.php on line 42
Database: tables
table: sc_tables
+------+----------+-------------+
| t_id | user_id | table_name |
+------+----------+-------------+
| 1 | 1 | bobs |
+------+----------+-------------+
table: sc_scores
+------+----------+-------------+-------+
| s_id | user_id | t_id | score |
+------+----------+-------------+-------+
| 1 | 1 | 1 | 50 |
+------+----------+-------------+-------+
PHP
<?php
include("config.php");
session_start();
$userId = (isset($_GET["user_id"]) && is_numeric($_GET["user_id"]) && (int)$_GET["user_id"] > 0) ? (int)$_GET["user_id"] : 0;
$query = "SELECT `a`.`table_name` FROM `sc_tables` AS `a` JOIN `sc_scores` AS `b` ON `a`.`t_id` = `b`.`t_id`";
$result = mysqli_query($db, $query);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
$smarty->assign('rows', $rows);
include("header.php");
$smarty->display('records.tpl');
?>
TPL (records.tpl)
<div>
<div>
The current rankings table:
<table>
{foreach from=$rows item="row"}
<tr>
<td>{$row.table_name}</td>
</tr>
{/foreach}
</table>
</div>
</div>
It would be much appreciated if someone can just point me in the right direction. thanks
There is no table_id field in the tables. So, you should have:
$query = "SELECT `a`.`table_name` FROM `sc_tables` AS `a` JOIN `sc_scores` AS `b` ON `a`.`t_id` = `b`.`t_id`";
The error says that the value FALSE is passed as argument to mysql_fetch_array($result). E.g. your mysqli_query() returns FALSE, not a mysqli_result object, as it should.
If problem persists after upper changes, without seeing any error, then you should use also mysqli_errno(), mysqli_error()and mysqli_error_list().
Good luck!
I have a table where ResultHRM column contains a textarea where the user can write comments. I would like to know, when I click on submit button how can update the correct line with the textarea content into my MySQL table NContrib ?
I read that textarea cannot have a value attribute.
My table NContrib has the following structure:
+-------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+----------------+
| IdVariantNContrib | mediumint(9) | NO | PRI | NULL | auto_increment |
| ID | varchar(30) | YES | | NULL | |
| Reference | varchar(20) | YES | | NULL | |
| ResultHRM | varchar(60) | YES | | NULL | |
+-------------------+--------------+------+-----+---------+----------------+
In my php page, I display this table like that:
<form method='POST' action='SaveValidation.php'>
<?php
require_once 'config.php'; //database connection
$sql='SELECT ID, Reference, ResultHRM FROM NContrib';
$PerformSql=mysqli_query($conn,$sql) or die(mysqli_error($conn));
?>
<table style="width:100%" border='1px' CELLSPACING='0' cellpadding='2'>
<tr>
<th> ID </th>
<th> Reference </th>
<th> ResultsHRM </th>
</tr>
<?php
while($rowNcontrib = mysqli_fetch_assoc($PerformSql)) {
echo "<tr><td> ".$rowNcontrib["ID"]." </td><td> ".$rowNcontrib["Reference"]." </td><td><textarea name='ResultHRM[]' id='ResultHRM[]' cols='30' rows='1'></textarea></td></tr>";
}
?>
</table>
<input type="submit" name="sendEcht" value="Submit" />
</form>
1) use $rowNcontrib['ResultHRM'] in beetween <textarea></textarea> to show value
2) Also use have use name='ResultHRM[]' this will give you a array of textarea values which you have updated but you will not get track of which value belongs to which ID. so name='ResultHRM[$id]'. here id should be the id of row
So your code should be
like
while($rowNcontrib = mysqli_fetch_assoc($PerformSql)) {
$id = $rowNcontrib["ID"];
echo "<tr><td> ".$rowNcontrib["ID"]." </td><td> ".$rowNcontrib["Reference"]." </td><td><textarea name='ResultHRM[$id]' id='ResultHRM[]' cols='30' rows='1'>".$rowNcontrib['ResultHRM ']."</textarea></td></tr>";
}
now in page SaveValidation.php check for this
if(isset($_POST['sendEcht'])){
echo "<pre>";print_r($_POST);die;}
this will show you something like this
Array
(
[ResultHRM] => Array
(
[3] => hello its test
[11] => test string
[10] =>
)
[sendEcht] => Submit
)
// here 3,11, 10 are my id's of table in your case it will be the id's of your table then you can easily update your table `ResultHRM` field
There are certain points that I would like to mention here:
If ResultHRM field is going to hold the values from textarea in form, I would suggest that you change the datatype. Currently, its varchar(60). I suggest, it should be text.
After fetching the data from the database, you are displaying it in the table structure. I would suggest, you add textarea and fill it with existing value. Let's assume you named textarea ResultHRM_ta
Once you will follow point#2, and submit the form, you can have textarea value in $_POST['ResultHRM_ta'] on SaveValidation.php.
Save the value in database.
Please note, I have mentioned the very basic outline for the process you need to follow. You will have to take care of security measures and coding standards on your own.
Tow solve this you can call a AJAX request with the code and pass id for each in the javascript method.
and in html code in the you can call method in each table row as follows:
<table style="width:100%" border='1px' CELLSPACING='0' cellpadding='2'>
<tr>
<th> ID </th>
<th> Reference </th>
<th> ResultsHRM </th>
</tr>
<?php
while($rowNcontrib = mysqli_fetch_assoc($PerformSql)) {
echo "<tr><td> ".$rowNcontrib["ID"]." </td><td> ".$rowNcontrib["Reference"]." </td><td><textarea name='ResultHRM' id='ResultHRM' cols='30' rows='1'></textarea></td><td><button type='button' onclick='update(".$rowNcontrib["ID"].")'">Update</button>;
}
?>
</table>
Hi I'm having trouble trying to split my db object result into the correct table for display.
Basically I'm trying to acheive this
<div class="panel"> $row->skill_group
<table class="collapse">
<thead>
<tr>
<th>$row->name</th>
</tr>
</thead>
<tbody>
<tr>
<td>$row->skill_name</td>
</tr>
<tr>
<td> $row->competency_name </td>
</tbody>
</table>
</div>
There can be many unique skill_groups and many skill_names but each person and their competency should only be displayed once for each skill.
My mysql returns the correct data however I can't figure out how to loop over the result so that I can split it in between the table that is nested from the div container.
For example the mysql result would be
======================================================================
| skill_group_name | skill_name | competency_name | name
======================================================================
| PHP Frameworks | Codeigniter | Working Knowledge | User name1
| PHP Frameworks | CakePHP | No Knowledge | User name1
| Database | T-SQL | Working Knowledge | User name2
======================================================================
and I need to fit it into the html structure above.
The result I'm after is
======================================================================
PHP Frameworks
======================================================================
| Codeigniter | Working Knowledge | User name1
| CakePHP | No Knowledge | User name1
======================================================================
Database
======================================================================
| T-SQL | Working Knowledge | User name2
======================================================================
I have managed to get the grouping of the skill_group sorted with:
if($row->skill_group_name != $skill_group_name)
{
echo '<div class="panel-heading"><a href="#" data-target=".skill'.++$counter.'" data-toggle="collapse">' . $row->skill_group_name;
$skill_group_name = $row->skill_group_name;
echo '</a></div>';
}
But I'm missing how to write the loops for the data table itself, how do I do this?
As I commented, I think you should save to an array, then implode() the sections:
//Just some fake data
$array[] = array('PHP Frameworks','Codeigniter','Working Knowledge','User name1');
$array[] = array('PHP Frameworks','CakePHP','No Knowledge','User name1');
$array[] = array('Database','T-SQL','Working Knowledge','User name2');
// Loop through the data
foreach($array as $row) {
// Save the table column html to array
$section[$row[0]][] = '<tr><td>'.$row[1].'</td><td>'.$row[2].'</td><td>'.$row[3].'</td></tr>';
}
// Loop through the section array you made
foreach($section as $title => $all) {
// Wrap it
echo '<div>'.$title;
// Implode
echo '<table>'.implode(PHP_EOL,$all).'</table>';
echo '</div>';
}
I'm working on a data monitor for solar panels.
Now i'm working on limited space, and getting a lot of data which is being logged on the database.
To downsize my space i was trying to find a way to make the datatables count everything every 15 minutes, and store it into a new table, and deleting the old tables.
I tried to do this with a cronjob, and later on tried to make a php script which would be handling it.
Now that code did not come close to what i was planning to have, and i'm stuck at this problem, and i know that there are probably people who do know the answer to this question.
I came across similar problems with searching through the site, but did not come across a "Count and Delete" question.
This to limit the space it uses.
Simply said, i'm trying to find a way with php to make it count and store the data records from "inverters" to "inverters_day", and deleting the excisting records from "inverters".
The Datatables are as following:
| timestamp | timestamp | No | CURRENT_TIMESTAMP
| inverter | int(11) | No |
| wh | int(11) | No |
| dcp | int(11) | No |
| dcc | float | No |
| efficiency | float | No |
| acf | int(11) | No |
| acv | float | No |
| temp | float | No |
| status | int(11) | No |
Example of data:
|2016-01-08 08:34:24|110134878|889901|0|0.05|0|49|55|2|1
|2016-01-08 08:34:59|110134878|889901|0|0.05|0|49|55|2|1
|2016-01-08 08:35:23|110048316|643076|0|0.05|0|49|55|1|1
Inverter_day is a duplication of the one above, structure it the same.
sorry, i forgot to add the code i tried.
if ($sql = mysqli_query ($conn, "SELECT COUNT (*) FROM logs WHERE timestamp < NOW() - INTERVAL 15 MINUTES")) {
$row_slt = mysqli_num_rows($sql);
if ($row_slt > 0 ) {
$sql = mysqli_query ($conn, "INSERT INTO inverter_day (timestamp, inverter, wh, dcp, dcc, efficiency, acf, acv, temp, status) SELECT timestamp, inverter, wh, dcp, dcc, efficiency, acf, acv, temp, status FROM logs WHERE timestamp NOT IN (select timestamp from inverter_day)");
} else if ($row_slt == 0) {
echo "<br> The Tables are up to date <br>";
} else {
echo "<br> Oops something went wrong. Please try again";
}
}
As i haven't had any further help with this, i just went on and left this part behind, untill i came across the INSERT SELECT feature.
The solution to the problem was the use of:
$query = "INSERT INTO enecsys_day (id, wh, dcpower, dccurrent, efficiency, acfreq, acvolt, temp, state) SELECT id, SUM(wh), SUM(dcpower), SUM(dccurrent), SUM(efficiency), SUM(acfreq), SUM(acvolt), SUM(temp), SUM(state) FROM enecsys GROUP BY id HAVING COUNT(id) > 1";
The full code i used:
<?php
mysql_connect($servername,$username,$password);
mysql_select_db($database);
$query = "INSERT INTO enecsys_day (id, wh, dcpower, dccurrent, efficiency, acfreq, acvolt, temp, state) SELECT id, SUM(wh), SUM(dcpower), SUM(dccurrent), SUM(efficiency), SUM(acfreq), SUM(acvolt), SUM(temp), SUM(state) FROM enecsys GROUP BY id HAVING COUNT(id) > 1";
$resultaat = mysql_query($query);
while ($row = mysql_fetch_array($resultaat))
{
?>
<tr>
<td><?php $row["id"]; ?></td>
<td><?php $row["SUM(wh)"]; ?></td>
</tr>
<br />
<?php
}
$delete = "DELETE FROM enecsys";
$dresultaat = mysql_query($delete);
?>
I have a simple my-sql table:
+----+----------+----------+-------------+-----------+
| id | Name | Father | National | Value |
+----+----------+----------+-------------+-----------+
| 1 | Daniel | David | American | 0 |
| 2 | Rebbeka | Craig | American | 0 |
| 3 | Robert | John | American | 0 |
| 4 | Arjun | Daneil | Indian | 0 |
| 5 | Ana | Peter | British | 0 |
+----+----------+----------+-------------+-----------+
I need to a php-script to query and fetch new single row every time it is executed. It may be based on ID.
About code/framework, i am using simple php5 with mysql on ubuntu server.
This is my code, the probelem is that it outputs whole of the Name,Father columns every time on call, i just want to print a single row everytime it is executed. and on every php script execution a new row should be printed based on id in ascending order.
<?php
$con = mysqli_connect('localhost','user','pass','database');
$result = mysqli_query($con,"select * from table");
while($row = mysqli_fetch_array($result)) {
echo "Name:" . $row['name'] . " " . "Father's Name:" . $row['father'];
echo "<br>";
}
mysqli_close($con);
?>
Every help is much appreciated.
the below code will help you get the output.
from next time when you ask any question pls add your code.
$link = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($link));
$query = "SELECT * FROM `emp` ORDER BY RAND() LIMIT 0,1;" or die("Error in the consult.." . mysqli_error($link));
$result = mysqli_query($link, $query);
//display information:
$row = mysqli_fetch_array($result);
echo $row["name"].$row["Father"].$row["National"].$row["Value"];
As i have no much details of what type of code/framework you have I am giving you a answer on the basis of what I understand
There will be two ways I can think of to fetch the data
1.
Change the Table Structure and add one more column called lastFetched and every-time you fetch the row update the particular row by 1 and else everything else to 0 so that next time when you fetch the row you already know which is the last row fetched by you. and you can do an increment to it.
2.
On the page you are fetching the result would have a hidden input where you can store the last data number letz say first time it is 0 when page loads
then your query will be
SELECT * from <tablename> LIMIT 0,1
and increase the value of the hidden input to +1
so next time you fetch the result will gives the query
SELECT * from <tablename> LIMIT 1,2
From the discussion we had in the comments I came to a conclusion that you are looking for this.
<table>
<tr>
<?php
if(isset($_POST['pullNextRecord'))
{
$whtrec=$_POST['whatrecord'];
$con = mysqli_connect('localhost','user','pass','database');
$result = mysqli_query($con,"select * from table LIMIT $whtrec, ++$whtrec");
echo "<input type='hidden' name='whatrecord' value=".$whtrec." />";
echo "<th>Name</th><th>Fathers Name</th></tr><tr>";
while($row = mysqli_fetch_array($result))
{
echo "<td>$row['name']</td><td>$row['father']</td>";
}
mysqli_close($con);
}
?>
<input type="submit" name="pullNextRecord" />