php db query to display certain user data (Smarty included) - php

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!

Related

Query SELECT * FROM multiple tables

I have two tables that looks like this:
Post table:
ID | photo | ident
-------------------------------------
80 | img/photo1 | ACH3882
81 | img/photo2 | SHD8837
82 | img/photo3 | SFF4837
83 | img/photo4 | DLL3266
Kudos table:
ID | photo_id | ident_id
-------------------------------------
1 | 80 | SHD8837
2 | 83 | ACH3882
3 | 82 | SHD8837
How it works: I am trying to add kudos system to my website. I have already set up the tables like shows above. Each user has its own ident. When a user press the kudos button, the ident of the user and the id for the photo is stored in the kudos table, like this:
$id = $_GET['id']; // get id through query string
$ident = $_SESSION["ident"];
$sql = "INSERT INTO kudos (photo_id, ident_id) VALUES ('$id', '$ident')";
if(mysqli_query($link, $sql)){
mysqli_close($link); // Close connection
header("location:index.php"); // redirects to all records page
exit;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
Now I want to display the number of kudos given for each photo. Currently I only query one table, but I need to query the second one also to get the value from that table also. This is how I query the first table:
<?php
$query = "SELECT * FROM post;
if ($result = $mysqli->query($query)) {
$num_rows = 0;
while ($row = $result->fetch_assoc()) {
$num_rows++;
/* <!-- Feed start --> */
echo "{$row['photo']}.";
echo '<a class="btn" href="kudos.php?id=';
echo "{$row['id']}";
echo '">';
echo '★ Give kudos</a>';
echo ' 0'; <- This is where I want the number count of kudos gives to show up.
... and so on
Can someone please help me out?
Select p.id,p.photo,p.indent from post p
Left join kudos k on
p.id = k.photo_id
Maybe you can try to join tables?
SELECT Post.id as post, count(Kudos.ident_id) as kudos
FROM Post
LEFT JOIN Kudos ON Post.id=Kudos.photo_id
GROUP BY Post.id;
This should return you smth like:
post_id ... kudosCount
Read more about joins here:
SQL joins

SQL query in PHP script keeps "losing" one row

Let's assume I have a table like this:
+------+---------+--------------+-------------+---------------+
| id | tstamp | product_id | name | configuration |
+------+---------+--------------+-------------+---------------+
| 3 | 15 | 02 | bike | abc |
| 2 | 16 | 03 | car | dfg |
| 1 | 11 | 04 | tree | ehg |
+------+---------+--------------+-------------+---------------+
When I run a simple query like
SELECT id, tstamp, product_id, name, configuration
FROM tl_iso_product_collection_item
ORDER BY `id` DESC
It returns 3 rows. As expected. Works, right? BUT, if I implement this query into a PHP script and try to fetch rows, theres always ONE missing. Always. Even in the most simple query. Where did I make a mistake?
Script looks like this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$connection = mysqli_connect('localhost', 'user', 'pw', 'db');
mysqli_set_charset($connection,"utf8");
$query = "SELECT id, tstamp, product_id, name, configuration
FROM table
ORDER BY `id` DESC "
$result = mysqli_query($connection, $query);
while ($row=mysqli_fetch_row($result)) {
echo $row[0];
echo $row[1];
echo $row[2];
echo $row[3];
echo $row[4];
}
mysqli_close($connection);
?>
This will result in displaying only 2 out of 3 rows. My question is, why tho? If I insert the query above directly into phpmyadmin it shows 3 results, not 2. What is wrong here? Am I missing something? Thanks in advance.
$fetch_allgemein = mysqli_fetch_array($result_allgemein);
$fetch_configuration = mysqli_fetch_array($result_configuration);
You are fetching the first record for each query result here already – so the internal “pointer” to the current record gets advanced to the second record in each result set, and therefor when you loop over the result using
while ($row=mysqli_fetch_row($result_allgemein)) {
later on, the first record is of course omitted.
You will need to reset the “pointer” using mysqli_result::data_seek if you want to get all records in your loops after you’ve already fetched the first record each.

How to store an array in a database column

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

User Wall PHP and MYSQL

I'm working on a big project a social networking site but now I'm stuck and i need your advice.
My problem is that I wan't to display everything like posts, videos and statuses into his profile.php under user timeline.
I got more than 40 Tables but let me specify what I wan't, I wan't to get data from these tables and how to display them on the profile.php timeline section ?
Status Table
------------------------------------------
ID | sMessage | sDate | uId
------------------------------------------
1 | Testing status | 2013/07/03 | 1
Videos Table
-----------------------------------------------------
ID | vName | vCode | vDate | uId
-----------------------------------------------------
1 | PHP and MYSQL | 2MvYwz | 2013/07/03 | 1
Users Table
-----------------------------------
ID | uName | JoinDate
-----------------------------------
1 | Tem Henov | 2013/07/03
And here is what i tried:
class userTimeline {
public function loadTimeline(){
dbConn();
$query = "SELECT
sMessage, sDate, vName, vDate, vCode
FROM status
INNER JOIN users
ON (status.uId = users.uId)
INNER JOIN videos
On (videos.uId = users.uId)
WHERE users.uId = '1'";
return $result = mysql_query($query);
}
}
and its loads the data fine but how to display that data in blocks like if its a status display in a separate block and if its a video display it in another block and how to order by date ?! any help is appreciated.
First : To Show data into various <div> first fetch them and show like,
1) Fetch all the record and store into a php array
$rows = array();
while($row = mysql_fetch_array(YOUR_QUERY))
{
$rows[] = $row;
}
2) Now Using foreach() loop use data fetched from query where ever you want
if(is_array($rows)) {
foreach($rows as $row) {
//do with $row or create some if,switch condition here !
}
}
For specific limits and tweaks study the result set we get from mysql_fetch_array() !
Second : To short data by date you can use multiple sorting (click here for
tutorial) but i think you should use MYSQL UNION to merge two
or more MySQL query results to get individual sorting result.

What is the correct way to join two tables in SQL?

I have two tables. The first table holds simple user data and has the columns
$username, $text, $image
(this is called "USERDATA").
The second table holds information about which users "follow" other users, which is set up with the columns
$username and $usertheyfollow
(this is called "FOLLOWS").
What I need to do is display the data individually to each user so that it is relevant to them. This means that userABC for instance, needs to be able to view the $text and $image inputs for all of the users whom he/she follows. To do this, I believe I need to write a sql query that involves first checking who the logged in user is (in this case userABC), then selecting all instances of $usertheyfollow on table FOLLOWS that has the corresponding value of "userABC." I then need to go back to my USERDATA table and select $text and $image that has a corresponding value of $usertheyfollow. Then I can just display this using echo command or the like...
How would I write this SQL query? And am I even going about the database architecture the right way?
With tables like so:
userdata table
______________________________
| id | username | text | image |
|------------------------------|
| 1 | jam | text | image |
+------------------------------+
| 2 | sarah | text | image |
+------------------------------+
| 3 | tom | text | image |
+------------------------------+
follows table
_____________________
| userId | userFollow |
|---------------------|
| 1 | 2 |
+---------------------+
| 1 | 3 |
+---------------------+
and use the following SQL:
SELECT userdata.text, userdata.image FROM follows LEFT JOIN userdata ON follows.userFollow = userdata.id WHERE follows.userId = 1
will get all the text and images that user with id '1' follows
As it turns out, neither of these answers were right. #jam6459 was closest.
The correct answer is the following:
SELECT userdata.text, userdata.image, follows.userFollow
FROM userdata
LEFT JOIN follows ON follows.userFollow = userdata.username
WHERE follows.userId = $username
I also found it easier to not have a username correspond to an Id as in jam's table example. This is because the same user can have multiple entries in "USERDATA". I instead used username as the Id.
function get_text_image($username)
{
$sql = "SELECT * FROM USERDATA where username='".$username."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row['text'];
echo $row['image'];
}
}
function display_data_of_followers($userid)
{
$sql = "SELECT usertheyfollow FROM follow WHERE userid = ".$userid."";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
get_text_image($row['usertheyfollow']);
}
}
display_data_of_followers($userid);

Categories