<?php
include 'connection.php';
session_start();
$noteinfo = array();
$noteinfo['note'] = $_POST['note'];
$_SESSION['noteinfo'] = $noteinfo;
if (isset($_POST['submit'])) {
if (empty($_POST['note'])) {
echo "Dobavete Komentar";
}
if (!empty($_SESSION['noteinfo'])) {
$check = mysqli_escape_string($conn,$_SESSION['userinfo']['fname']);
print_r($_SESSION['userinfo']);
$sql = "INSERT INTO users (user_fname,user_mname,user_lname,user_login,user_email,user_phone)
VALUES ('{$_SESSION['userinfo']['fname']}', '{$_SESSION['userinfo']['mname']}', '{$_SESSION['userinfo']['lname']}', '{$_SESSION['userinfo']['login']}', '{$_SESSION['userinfo']['email']}', '{$_SESSION['userinfo']['phone']}')";
$sql1 = "INSERT INTO addresses (address_line_1,address_line_2,address_zip,address_city,address_province,address_country)
VALUES ('{$_SESSION['addressinfo']['adr1']}', '{$_SESSION['addressinfo']['adr2']}', '{$_SESSION['addressinfo']['zip']}', '{$_SESSION['addressinfo']['city']}', '{$_SESSION['addressinfo']['provinciq']}', '{$_SESSION['addressinfo']['durjava']}')";
$sql2 = "INSERT INTO notes (note_text)
VALUES ('{$_SESSION['noteinfo']['note']}')";
$sql3 = "INSERT INTO users_addresses (ua_user_id,ua_address_id)
SELECT users.user_id,addresses.address_id
FROM ( VALUES () )";
if (mysqli_query($conn,$sql)) {
echo "Added";
if (mysqli_query($conn,$sql1)) {
echo "Added";
if (mysqli_query($conn,$sql2)) {
echo "Added";
if (mysqli_query($conn,$sql3)) {
echo "Mai stana toq put";
header("refresh:3 ; url=profile.php");
}
}
}
}
else{
echo "Error";
}
}
else{
header("refresh:1 ; url=zapiski.php");
}
}
?>
My question is for $sql3: I want when the forms are completed to fill the users_addresses with the id of the user and the id from the address tables.But for now the SQL doesn't fill nothing in the table users_addresses. These are my tables:
When a user is filling in values in an application and you need to look up ids for them, then a typical way to write the query looks like this:
INSERT INTO users_addresses (ua_user_id, ua_address_id)
VALUES ( (SELECT u.user_id FROM users u WHERE u.username = ?),
(SELECT a.address_id FROM address a WHERE a.address = ?)
);
That is, you are passing parameters into the query, using the parameters to look up ids, and then using those ids to insert into the junction table.
You seem to be missing the VALUES() function in your INSERT.
INSERT INTO users_addresses(ua_user_id,ua_address_id)
It should be,
INSERT INTO users_addresses(ua_user_id,ua_address_id) VALUES(some_variable,some_variable)
You could also do,
INSERT INTO users_addresses SET ua_user_id=some_variable, ua_address_id=some_variable
When it comes to selecting the data, you will need to JOIN your tables. I suggest a LEFT JOIN in this matter. It is important, that the id's that you are going to match against one another in the JOIN are coherent, so that you are able to link the tables together. It is then up to you whether you want a specific match or not in your condition, if you are parsing a user_id (i.e. WHERE clause).
Example selecting specific match:
SELECT
users_addresses.ua_id,
addresses.address_id
FROM
users_addresses
LEFT JOIN
users ON users_addresses.ua_user_id = users.user_id
LEFT JOIN
addresses ON users_addresses.ua_address_id = addresses.address_id
WHERE
users_addresses.ua_id = $some_id
Example selecting all matches:
SELECT
users_addresses.ua_id,
addresses.address_id
FROM
users_addresses
LEFT JOIN
users ON users_addresses.ua_user_id = users.user_id
LEFT JOIN
addresses ON users_addresses.ua_address_id = addresses.address_id
Let me know if this is what you are looking for, and whether you need something elaborated.
An important note, you should look into prepared statements since you are using the mysqli_* extension. It will improve your security a lot, as you are open to SQL-injections at the moment.
Related
I have two different tables, one named users, and another named transactions. Transactions contains wallet1, wallet2, amount. Users contains user details such as firstname, lastname, and wallet. I am trying to display the corresponding first name and last name, depending on whether or not the SESSION_wallet is equal to wallet1 or wallet2 within transactions. I tried searching for a while, and came up with a solution for showing the correct display name for the first and last name making the transfer, however, I am trying to make it display the correct value for "Transfer to:"
Here is some of my code to get a better understanding of what I mean:
MySQLi Query:
$result2 = mysqli_query($link, "SELECT * FROM transactions INNER JOIN users ON transactions.wallet1 = users.wallet WHERE transactions.wallet1 = '" . $_SESSION["wallet"] . "' OR transactions.wallet2 = '" . $_SESSION["wallet"] . "' Order by transactions.id DESC LIMIT 5 ");
PHP Code:
<?php
if(mysqli_num_rows($result2) > 0)
{
while($row = mysqli_fetch_array($result2))
{
?>
The table that needs to display the transfer from, and transfer to:
<?php
if ($_SESSION["wallet"] == $row["wallet1"]) {
echo "<td>Transfer to ".$row["firstname"]." ".$row["lastname"]."</td>";
}
else if ($_SESSION["wallet"] == $row["wallet2"]) {
echo "<td>Transfer from ".$row["firstname"]." ".$row["lastname"]."</td>";
}
?>
Right now my tables are only showing the first and last name of the user that made the Transfer, however, I need it to display the first and last name of the user that the transaction is made to as well. The else if code is working correct, but the first part is not showing the corresponding value.
You will need to JOIN your transactions table to your users table twice, once to get each users name. Then to avoid duplicate column names overwriting the results in the output array, you will need to use column aliases. Something like this should work:
$result2 = mysqli_query($link, "SELECT t.*,
u1.firstname AS w1_firstname,
u1.lastname AS w1_lastname,
u2.firstname AS w2_firstname,
u2.lastname AS w2_lastname
FROM transactions t
INNER JOIN users u1 ON t.wallet1 = u1.wallet
INNER JOIN users u2 ON t.wallet2 = u2.wallet
WHERE t.wallet1 = '{$_SESSION["wallet"]}'
OR t.wallet2 = '{$_SESSION["wallet"]}'
ORDER BY t.id DESC
LIMIT 5 ");
Then you can access each user's names as $row['w1_firstname'] etc.:
if ($_SESSION["wallet"] == $row["wallet1"]) {
echo "<td>Transfer to ".$row["w2_firstname"]." ".$row["w2_lastname"]."</td>";
}
else if ($_SESSION["wallet"] == $row["wallet2"]) {
echo "<td>Transfer from ".$row["w1_firstname"]." ".$row["w1_lastname"]."</td>";
}
Note that ideally you should use a prepared query for this, for example:
$stmt = $link->prepare("SELECT t.*,
u1.firstname AS w1_firstname,
u1.lastname AS w1_lastname,
u2.firstname AS w2_firstname,
u2.lastname AS w2_lastname
FROM transactions t
INNER JOIN users u1 ON t.wallet1 = u1.wallet
INNER JOIN users u2 ON t.wallet2 = u2.wallet
WHERE t.wallet1 = ?
OR t.wallet2 = ?
ORDER BY t.id DESC
LIMIT 5");
$stmt->bind_param('ss', $_SESSION["wallet"], $_SESSION["wallet"]);
$stmt->execute();
$result2 = $stmt->get_result();
I'm working on a system, and this module is supposed to echo the contents of the database.
It worked perfectly until I added some JOIN statements to it.
I've checked and tested the SQL code, and it works perfectly. What's not working is that part where I echo the content of the JOINed table.
My code looks like this:
$query = "SELECT reg_students.*, courses.*
FROM reg_students
JOIN courses ON reg_students.course_id = courses.course_id
WHERE reg_students.user_id = '".$user_id."'";
$result = mysqli_query($conn, $query);
if (mysqli_fetch_array($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
echo $row["course_name"];
echo $row["course_id"];
The course_name and course_id neither echo nor give any error messages.
UPDATE: I actually need to increase the query complexity by JOINing more tables and changing the selected columns. I need to JOIN these tables:
tutors which has columns: tutor_id, t_fname, t_othernames, email, phone number
faculty which has columns: faculty_id, faculty_name, faculty_code
courses which has columns: course_id, course_code, course_name, tutor_id, faculty_id
I want to JOIN these tables to the reg_students table in my original query so that I can filter by $user_id and I want to display: course_name, t_fname, t_othernames, email, faculty_name
I can't imagine that the user_info table is of any benefit to JOIN in, so I'm removing it as a reasonable guess. I am also assuming that your desired columns are all coming from the courses table, so I am nominating the table name with the column names in the SELECT.
For reader clarity, I like to use INNER JOIN instead of JOIN. (they are the same beast)
Casting $user_id as an integer is just a best practices that I am throwing in, just in case that variable is being fed by user-supplied/untrusted input.
You count the number of rows in the result set with mysqli_num_rows().
If you only want to access the result set data using the associative keys, generate a result set with mysqli_fetch_assoc().
When writing a query with JOINs it is often helpful to declare aliases for each table. This largely reduces code bloat and reader-strain.
Untested Code:
$query = "SELECT c.course_name, t.t_fname, t.t_othernames, t.email, f.faculty_name
FROM reg_students r
INNER JOIN courses c ON r.course_id = c.course_id
INNER JOIN faculty f ON c.faculty_id = f.faculty_id
INNER JOIN tutors t ON c.tutor_id = t.tutor_id
WHERE r.user_id = " . (int)$user_id;
if (!$result = mysqli_query($conn, $query)) {
echo "Syntax Error";
} elseif (!mysqli_num_rows($result)) {
echo "No Qualifying Rows";
} else {
while ($row = mysqli_fetch_assoc($result)) {
echo "{$row["course_name"]}<br>";
echo "{$row["t_fname"]}<br>";
echo "{$row["t_othernames"]}<br>";
echo "{$row["email"]}<br>";
echo "{$row["faculty_name"]}<br><br>";
}
}
I was using this query to connect my student table and attendance table,
My Problem is, sometimes, attendance table has no value.
It's not returning any value.
<?php
if($_SERVER['REQUEST_METHOD']=="POST"){
include('include/connection.php');
showData();
}
function showData(){
global $connect;
$teacher_id = $_POST['teacher_id'];
$subject_id = $_POST['subject_id'];
$date = $_POST['date'];
$query ="
SELECT s.student_name
, s.student_number
, s.student_section
, s.subject_id
, s.fingerprint_id
, s.teacher_id
, a.status
FROM tbl_student s
LEFT
JOIN tbl_attendance a
on s.subject_id=a.subject_id
WHERE s.subject_id = '$subject_id'
and a.date='$date'
and s.teacher_id = '$teacher_id';";
$result =mysqli_query($connect,$query);
$number_of_rows = mysqli_num_rows($result);
$temp_array=array();
if($number_of_rows>0){
while($row=mysqli_fetch_assoc($result)){
$temp_array[]=$row;
}
}
header('Content-Type: application/json');
echo json_encode(array("student"=>$temp_array));
mysqli_close($connect);
}
?>
What I want to achive is even if attendance table has no value,
I can still see the student fields.
Is it even possible with SQL query? Thanks
You have to move the fields of table attendance from where to the on condition:
$query ="SELECT student.student_name,student.student_number,student.student_section,student.subject_id,student.fingerprint_id,student.teacher_id,attendance.status
FROM tbl_student student
LEFT JOIN tbl_attendance attendance on student.subject_id=attendance.subject_id and attendance.date='$date'
WHERE student.subject_id='$subject_id' and student.teacher_id='$teacher_id';";
Because first the join Statement will be executed and then the where, if you access the table tbl_attendance in where ans all the columns are null, they will filtered out.
Hint: read about prepared Statements to provide SQL-injection
SELECT student.student_name,student.student_number,student.student_section,student.subject_id,student.fingerprint_id,student.teacher_id,attendance.status
FROM tbl_student student
LEFT JOIN tbl_attendance attendance on student.subject_id=attendance.subject_id and attendance.date='$date'
WHERE student.subject_id='$subject_id' and student.teacher_id='$teacher_id';
Try above code.Hope this will helps.
As you had made condition on student table using attendance.date='$date' on WHERE clause it exclude that record which are not satisfy this condition.
So instead of where i had put that condition through ON clause on LEFT JOIN.
This will achieve your goal.
I have 2 table's:
Users (id, username, email, avatar, etc...);
Friends (id, user1, user2, status);
Now I want to build on my profile page an list of my friends with there avatar(s). I'm trying for like 4 hours by myself but i don't get it... :(
BTW: this is an error i got!
Notice: Array to string conversion in /home/reduaqi158/domains/reduankurtaj.eu/public_html/snapfriends/vrienden.php on line 26
This is what i have right now:
<?php
error_reporting(E_ALL);
session_start();
$username = $_SESSION['username'];
$status = 2;
include "includes/conn.php";
$vrienden=mysqli_query($server,"SELECT * FROM vrienden WHERE status='$status' && vriend1='$username' || vriend2='$username' ");
$vriend_list = array();
while($row = mysqli_fetch_array($vrienden))
{
if ($row['vriend1'] == $username) {
$vriend_list[] = $row['vriend2'];
}
else {
$vriend_list[] = $row['vriend1'];
}
}
echo json_encode($vriend_list);
$foto=mysqli_query($server,"SELECT prof_pic FROM users WHERE username='$vriend_list['vriend1''vriend2']' ");
while($row2 = mysqli_fetch_array($foto)) {
echo "<img class='img-rounded' src=assets/profiel/".$row2['prof_pic']." alt='Card image cap'>";
}
?>
json_encode output:
["ja","amando"]
Someone who can help me pls :)
Your initial approach is very confusing.
Almost everything in your code can be substituted by single SQL query.
You can use JOIN to get all your friends with their avatars in one go:
SELECT u.username as username, u.avatar as avatar,.... <== all columns which you need
FROM `friends_table` f <== your friends table
JOIN `users_table` u <== your users table
ON (f.user1 = u.id) <== notice that i join on user1 column
WHERE u.username = '$username' && f.status = '$status'
UNION
SELECT u.username as username, u.avatar as avatar,.... <== same columns
FROM `friends_table` f <== your friends table
JOIN `users_table` u <== your users table
ON (f.user2 = u.id) <== notice that i join on user2 column
WHERE u.username = '$username' && f.status = '$status'
By this query you select all users who are in a friendship with your $username. You need union because you don't know in which field (user1 or user2) your $username is located.
NOTE: I strongly suggest using prepared statements instead of just putting '$var' inside SQL query to prevent SQL Injection.
After executing this query you can parse results and display avatars in such a way:
while($row = mysqli_fetch_array($vrienden, MYSQLI_ASSOC))
{
echo "<img class='img-rounded' src=assets/profiel/".$row['avatar']." alt='Card image cap'>";
}
I hope you got the idea.
in your while statement you have to declare a value for the array. like array[0] = value. so that you know that array position 0 has a certain value. Like what I did here below. Don't know if it's in PHP like this but certain in .net you have to declare the location of a value in an array.
while($row = mysqli_fetch_array($vrienden))
{
if ($row['vriend1'] == $username) {
$vriend_list[0] = $row['vriend2'];
}
else {
$vriend_list[1] = $row['vriend1'];
}
}
and the following
$foto=mysqli_query($server,"SELECT prof_pic FROM users WHERE username='$vriend_list['vriend1''vriend2']' ");
shouldn't it be $vriend_list['vriend1'] . $vriend_list['vriend2']'
you have to use a connect character (the . in PHP)
Im making a blog like system using HTML, CSS, PHP and MySQl.
The site is made up of three tables.
user (id, username, password, email)
posts (postid, title, post)
comments (postid, id, comment, commentid) postid coming from posts and id from user.
I am trying to display all of the comments and the users username who left them for a certain post.
When i use this query in phpmyadmin:
SELECT user.username, comments.comment FROM user INNER JOIN comments on user.id=comments.id where postid=1
It shows what i need.
When i add it into php i get a blank page.
<?php
//echo "1";
session_start();
$connect = mysql_connect('localhost', 'root', 'root') or die("Couldn't connect");
mysql_select_db("com541blog") or die("Couldn't connect to database");
//echo "2";
//$postid = $_GET['type'];
$_SESSION['postid'] = $postid;
//echo "3";
$query_comments = mysql_query("SELECT user.username as username, comments.comment as comment FROM user INNER JOIN comments on user.id=comments.id WHERE postid='1'");
$info = mysql_fetch_array($query_comments);
$username = $info['username'];
$comment = $info['comment'];
echo $username;
echo $comment;
?>
Thanks in advance for the help :)
You're not executing any query.
$rs = mysql_query($query_comments);
$info = mysql_fetch_array($rs);
Your first line has an error I suspect, ie missing 'c' near the end of 'connect'.
include("db_connet.php"); should be include("db_connect.php");
Also, missing a semi-colon ;. This:
$query_comments = ("SELECT user.username, comments.comment
FROM user INNER JOIN comments on user.id=comments.id
where postid=1")
Should read:
$query_comments = ("SELECT user.username, comments.comment
FROM user INNER JOIN comments on user.id=comments.id
where postid=1");
Also, not bad practice to qualify each of your column names with a table name eg user.username as you're doing. But you might prefer eg the following more concise syntax using table aliases:
$query_comments = ("SELECT u.username, c.comment
FROM user u INNER JOIN comments c on u.id = c.id
where c.postid = 1");
(Note the table aliases don't need to be a single letter, so can be handy reducing a table name such as "ManufacturerSuppliedPartsListData_Feb01", to eg "mpl", without losing their meaning. Or eg if you've got "Customers" and "Credit" instead of just "c" you might use eg "cust" and "cred")
You need to specify mysql_query in PHP ... Else your query will not be executed
Like :
$query_comments = mysql_query("SELECT user.username, comments.comment FROM user INNER JOIN comments on user.id=comments.id where where postid=1");