mardi 5 mai 2015

select slow because of unused inner join

I have two tables:

CREATE TABLE `A` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
CREATE TABLE `B` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `a_id` int(11) NOT NULL,
  `c_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `IX_a_id` (`a_id`),
  KEY `IX_c_id` (`c_id`),
  CONSTRAINT `a_id_ibfk_1` FOREIGN KEY (`a_id`) REFERENCES `A` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;

They have a couple million rows each.

explain select count(*) FROM B inner join A on B.a_id = A.id WHERE B.c_id = 7;
+----+-------------+-------+--------+-----------------------+------------+---------+--------------------+--------+-------------+
| id | select_type | table | type   | possible_keys         | key        | key_len | ref                | rows   | Extra       |
+----+-------------+-------+--------+-----------------------+------------+---------+--------------------+--------+-------------+
|  1 | SIMPLE      | B     | ref    | IX_a_id,IX_c_id       | IX_c_id    | 4       | const              | 116624 | Using where |
|  1 | SIMPLE      | A     | eq_ref | PRIMARY               | PRIMARY    | 4       | test1.B.a_id       |      1 | Using index |
+----+-------------+-------+--------+-----------------------+------------+---------+--------------------+--------+-------------+

Now, I can't understand why mysql is unable to ignore the un-needed inner join to A which kills performance. i.e., the following query is equivalent to the above:

select count(*) from B where B.c_id = 7

which should be easy to infer since B.a_id can't be null and B.a_id has a constraint to the unique key A.id

Is there a way to make mysql understand this ?

MySL tables are not UTF8 even though I instructed Hibernate to do create them with UTF8

I'm using a Spring Boot application and even though I instructed h]Hibernate to make new tables in UTF8, all new tables are in latin1.

spring.jpa.properties.hibernate.connection.characterEncoding=utf-8
spring.jpa.properties.hibernate.connection.CharSet=utf-8
spring.jpa.properties.hibernate.connection.useUnicode=true

I'm using Hikari.

insert multiple values in mysql in a nested select

I'm fairly new to sql. This might be basic. I have two tables one with groups and one with members, I want to link them up so that a third table contains id_group and id_member. The value MYGROUP is supplied during the import. I tried this:

insert ignore into member_group (id_group, id_member) 
values ( ( select id_group from group where group_name='MYGROUP' ) ,
( select id_member from member ) );

But I end up with one row in member_group containing a null value.

on it's own this yields 1 for example:

select id_group from group where group_name='MYGROUP';
+----------+
| id_group |
+----------+
|        1 |
+----------+

on it's own this yields a list of id_members

mysql> select id_member from member;
+-----------+
| id_member |
+-----------+
|       123 |
|       456 |
|       789 |

I want member_group to then look like this

+-----------+----------+
| id_group  |id_member |
+-----------+----------+
|         1 |      123 |
|         1 |      456 |
|         1 |      789 |

How can I do this (without resorting to shell scripts, for loops and sed) ?

Bandwidth vs database querying

I display images that I want the user to be able to delete. I do this with an AJAX request.

Is it best practise to:

  1. Pass just the ID of the image, use mysql to find what the filename of that record is, and then delete the file?

OR

  1. Pass the ID and the src of the image so I can just delete the image right away without looking it up?

One uses more bandwidth, the other more processing power.

Either way I need the ID because I have to do delete the record.

How to populate javafx TableView column with values from MySQL generated column?

I am using generated columns introduced in MySQL version 5.7. How to use values from those columns to populate a javafx TableView? Excerpts from the code which I am using to populate the TableView:

public void processQuery(){
    try {
        int i = (Integer)aList.get(arrayObjectNumber);
        System.out.println(i);
        String aQuery = "select * from sale_invoice_details "
                        + "where sale_invoice_id = "+  i;
        rs = con.createStatement()
                .executeQuery(aQuery);
        System.out.println("executed aQuery");
        while(rs.next()) {
            System.out.println(rs);
        sale_invoice_details_array
                 .add(new s_i_d
                        (rs.getInt("id"), 
                        rs.getString("name"), 
                        rs.getFloat("quantity"),
                        rs.getFloat("amount_generated")));}
        processQueryB(i);
         } catch (Exception e) {
        System.out.println(e);
    }
}
  ...

public class s_i_d {
    private IntegerProperty id;
    private StringProperty name;
    private FloatProperty quantity;
    private FloatProperty amount_generated;
    private s_i_d(Integer id, String name, Float quantity, Float amount_generated) {
        this.id = new SimpleIntegerProperty(id);
        this.name = new SimpleStringProperty(name);
        this.quantity = new SimpleFloatProperty(quantity);
        this.amount_generated = new SimpleFloatProperty(amount_generated);
    }
    public IntegerProperty idProperty() {return id;}
    public StringProperty nameProperty() {return name;}
    public FloatProperty quantityProperty() {return quantity;}
    public FloatProperty amount_generatedProperty() {return amount_generated;}
}

In the console:

    ...
   executed aQuery
   com.mysql.jdbc.JDBC4ResultSet@248423af
   java.sql.SQLException: Column 'amount_generated' not found.
    ...

MySQL table code:

CREATE TABLE `sale_invoice_details` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `rate` float DEFAULT NULL,
  `quantity` float DEFAULT NULL,
  `discount` float DEFAULT NULL,
  `amount` float DEFAULT NULL,
  `sale_invoice_id` int(11) DEFAULT NULL,
  `product_id` int(11) DEFAULT NULL,
  `amout_generated` float GENERATED ALWAYS AS (quantity*rate) VIRTUAL,
  PRIMARY KEY (`id`),
  KEY `fk_sale_invoice_id_idx` (`sale_invoice_id`),
  KEY `fk_product_id_idx` (`product_id`),
  CONSTRAINT `fk_product_id` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_sale_invoice_id` FOREIGN KEY (`sale_invoice_id`) REFERENCES `sale_invoice` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=32303 DEFAULT CHARSET=latin1$$

How can I rebuild indexes and update stats in MySQL innoDB?

I have experience with MS SQL server where it is possible and useful to update statistic and rebuild indexes. I can't find such option in MySQL innoDB, is there such option? If not, how MySQL database create an execution plan? Does the MySQL update indexes and statistic with every UPDATE and INSERT?

Choose from various dates using date time picker

This button filters the datagridview using datetimepicker. What should I do if I want to filter it between dates?

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

    MySqlConn = New MySqlConnection
    MySqlConn.ConnectionString = "Server = Localhost; database = venuesdb; user id = root; Password = "
    Dim SQLDataAdapter As New MySqlDataAdapter
    Dim DatabaseDatSet As New DataTable
    Dim Bindsource As New BindingSource        
    Try
        MySqlConn.Open()
        Dim Query = "Select * From venuesdb.cost where EventDate  = ('" & DateTimePicker1.Text & "')"
        Command = New MySqlCommand(Query, MySqlConn)
        SQLDataAdapter.SelectCommand = Command
        SQLDataAdapter.Fill(DatabaseDatSet)
        Bindsource.DataSource = DatabaseDatSet
        DataGridView1.DataSource = Bindsource
        SQLDataAdapter.Update(DatabaseDatSet)
        MySqlConn.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    MySqlConn.Dispose()
End Sub

Simpler way for this query: If {current date} is a {weekly/fortnightly/monthly} repeat/multiple of {start_date}

We have a table for scheduled_jobs, this table includes the following two collumns:

Repeat Type: Weekly/Fortnightly/Monthly

Beginning Date: The date it will repeat from, i.e. if repeat type is monthly and beginning date is set to 2015-12-05, it will repeat on the fifth of each month.

The below query is a snippet of code that is currently being used:

<?php
    foreach(range(1,100) as $num)
    {
        $numtimestwo = $num * 2;

        $query = "SELECT * FROM scheduled_jobs WHERE deleted != TRUE AND ((DATE_ADD(DATE(beginning_date), INTERVAL $num MONTH) = CURDATE() AND repeat_type = 'monthly') OR (DATE_ADD(DATE(beginning_date), INTERVAL $numtimestwo WEEK) = CURDATE() AND repeat_type = 'fortnightly') OR (DATE_ADD(DATE(beginning_date), INTERVAL $num WEEK) = CURDATE() AND repeat_type = 'weekly'))";

        // If result is not empty, process the scheduled job
    }
?>

But I've noticed some problems, this will eventually stop working as beginning_date gets older and older, and it seems like there should be a better solution to this.

How to structure this relational database

Basically I'll be having 3 tables that have relation. They are: users, departments and company.

The issue I have is this:

  • A company can have many departments
  • A department can only be attached to one company
  • A user can only be part of one company
  • A user can be part of many departments

This is essentially what the table relation would look like:

                    ____________________
                    | | | |            |
                    | | | |            |
--------      --------------      -----------
| user |      | department |      | company |
--------      --------------      -----------
 |   |         | | | | |               |
 |   |         | | | | |               |
 |   ___________________               |
 |                                     |
 |                                     |
 |                                     |
 _______________________________________

The above multiple | lines show an option, so the "company" above has 4 departments and so on.

Now my question is this, How should I structure the relation tables?

Should I have user_departments, user_company and company_departments tables?

That would essentially look like this:

--------------------
| user_departments |
--------------------------------
| id | user_id | department_id |
--------------------------------

----------------
| user_company |
-----------------------------
| id | user_id | company_id |
-----------------------------

-----------------------
| company_departments |
-----------------------------------
| id | company_id | department_id |
-----------------------------------

Or are there any other alternatives for me to consider/implement instead of the path I'm going as it seems it'll just keep growing complex?

MySQL result variable not functioning PhP [duplicate]

This question already has an answer here:

My $result variable is causing the error: ( ! ) Parse error: syntax error, unexpected '$result' (T_VARIABLE) in C:\wamp\www\testFunction.php on line 30

Ive search the other threads and I think its coded correctly

<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);

if (isset($_POST['delete']) && isset($_POST['ContractorID']))
{
  $ContractorID  = get_post($conn, 'ContractorID');
  $query  = "DELETE FROM Professionals WHERE 'ContractorID' ='$ContractorID'";
  $result = $conn->query($query);
  if (!$result) echo "DELETE failed: $query<br>" .
    $conn->error . "<br><br>";
}

if (isset($_POST['Name'])   &&
    isset($_POST['Title'])    &&
    isset($_POST['Company']) &&
    isset($_POST['Address']) &&
    isset($_POST['ContractorID']))
{
  $Name         = get_post($conn, 'Name');
  $title        = get_post($conn, 'Title');
  $Company      = get_post($conn, 'Company');
  $Address      = get_post($conn, 'Address');
  $ContractorID = get_post($conn, 'ContractorID');
        $query    = "INSERT INTO Professionals VALUES" .
                    "('$Name', '$title', '$Company', '$Address', '$un');"


  $result   = $conn->query($query);


  if (!$result) echo "INSERT failed: $query<br>" .
    $conn->error . "<br><br>";
}

echo <<<_END
<form action="AthleteData.php" method="post"><pre>
Name         <input type="text" name="Name">
Title        <input type="text" name="Title">
Company      <input type="text" name="Company">
Address      <input type="text" name="Address">
                  <input type="submit" value="ADD RECORD">
</pre></form>
_END;

$query  = "SELECT 'Name', 'Title', 'Company', 'Address' FROM Professionals WHERE Athlete = '$un'";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);

$rows = $result->num_rows;
//'<table>';
for ($j = 0 ; $j < $rows ; ++$j)
{
  $result->data_seek($j);
  $row = $result->fetch_array(MYSQLI_NUM);
//'<td>';
  echo <<<_END
<pre>
   Name $row[0]
   Title $row[1]
   Company $row[2]
   Address $row[3]
   ContractorID $row[4]
</pre>
<form action="AthleteData.php" method="post">
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="ContractorID" value="$row[4]">
<input type="submit" value="DELETE RECORD"></form>
_END;
//'</td>';
}
//'</table>';

$result->close();
$conn->close();

function get_post($conn, $var)
{
  return $conn->real_escape_string($_POST[$var]);
}
?>

This is the snippet that is causing problems. I included all the code for reference if needed previously. Thank you for your help.

if (isset($_POST['Name'])   &&
    isset($_POST['Title'])    &&
    isset($_POST['Company']) &&
    isset($_POST['Address']) &&
    isset($_POST['ContractorID']))
{
  $Name         = get_post($conn, 'Name');
  $title        = get_post($conn, 'Title');
  $Company      = get_post($conn, 'Company');
  $Address      = get_post($conn, 'Address');
  $ContractorID = get_post($conn, 'ContractorID');
        $query    = "INSERT INTO Professionals VALUES" .
                    "('$Name', '$title', '$Company', '$Address', '$un');"


  $result   = $conn->query($query);


  if (!$result) echo "INSERT failed: $query<br>" .
    $conn->error . "<br><br>";
}

The compiler is saying that the $result is unexpected and I dont know why. The other posts say to write the query into the conn->query parameter. I did by writing the query into a variable.

Duplicated data in MVC linq query

I have a question regarding linq query. My controller code looks like this:

public ActionResult Show_Trans(int id = 0)
    { 
        //this checks if the id exists in the database
        var check = db.Student_Trans.Where(s=>s.student_id == id).FirstOrDefault();
        // if not, show a javascript alert
        if(check == null){
            return Content("<script type='text/javascript'>alert('No transaction so far.');</script>");
        }

        // this return the data that equals to the id
        return PartialView(db.Payments_vw.Where(s=>s.student_id == id).ToList());

    }

In my database view (Payments_vw), for example, the student with student id of 2 has 3 transactions namely: Miscellaneous, Parents Share, Uniform.

The question is: when I tried to view it in my Views, it returns the exact number of rows but the datas are repeated or should I say, all are in Miscellaneous transaction but the Parents Share and Uniform are not shown. Why? Any help is greatly appreciated. Thanks.

Here is my view:

@model IEnumerable<Billing_App.Models.Payments_vw>

<h3><b>List of Transaction Logs</b></h3>
<table class="table">
<tr>
    <th>Student Name</th>
    <th>Transaction Name</th>
    <th>Transaction Amount</th>
    <th>Amount Paid</th>
    <th>Deadline</th>
    <th>Remaining Balance</th>
</tr>
@foreach (var item in Model)
{ 
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.student_lastname)&nbsp;, @Html.DisplayFor(modelItem => item.student_firstname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.trans_name)
        </td>
        <td>
            P &nbsp; @Html.DisplayFor(modelItem => item.trans_amount)
        </td>
        <td>
            P &nbsp; @Html.DisplayFor(modelItem => item.payment)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.trans_deadline)
        </td>
    </tr>

}

I think there's something wrong with my linq query.

Convert VB Date () and DateAdd function to PHP

I have a simple VB function that shows records from current date and anything back to 21 days old.

WHERE date_added between date() and DateAdd('d', -21, Date())

How can I get the same effect using php?

Man thanks Frank

mysql-python installation error on Windows

everybody. I am trying to get running with Django, but I'm stuck on the last process of installation - the mysql-python downloading and installation. This is the screenshot of Command Prompt:

Command Prompt screenshot

Can somebody tell me if this will affect the Django learning process at all (I know already that it comes with SQLite) and how to fix it if I have to?

Persistent mysql connection, regardless of users connected?

I want to have ONE single mysql-connection used by EVERY user that selects the data all the time and updates it if specific conditions are met (like a placed bid). Most preferably even then if no user is visiting the website, if that's even possible?

So, in the last days I'm google'ing all the time, trying so hard to figure out to solve my issue, but it seems there are no people with enough knowledge to help me with my problem. So I try to ask my question as simple as possible without confusing you with my code. (But if you're interested seeing the code: http://ift.tt/1chTFL5)

However, this is all about an auction website with live-countdown-timer and I just want to run a node.js server that SELECTs data every second and sends it to a WebSocket to show all users visiting that website the countdown and price-updates (on bids) in realtime.

I accomplished this whole task by using single-mysql-queries but then I ran into errors. Then the author of the GitHub node-mysql-module suggested me to use a MySQL Pool. But there is like no content at all to find about my specific aim stated in my first sentence of this question.

Now I want to ask in general, how could I accomplish this and is this even possible or does at least one user has to be on my website?

What would the code/code-structure/logical process look like?

And I guess I don't need to close the connection at all, so I won't need functions like connection.end()?

1064 error with CodeIgniter in ci_sessions table

// Run the update query
    $this->CI->db->where('session_id', $this->userdata['session_id']);
    $this->CI->db->update($this->sess_table_name, array('last_activity' => $this->userdata['last_activity'], 'user_data' => $custom_userdata));

I have a problem using sessions in CodeIgniter, I downloaded de las CI version and I have to modify many things to make it works, but, I have this f.. problem, when I'm trying to login in my web, I have this problem, with 1064 error MySQL

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET `last_activity` = 1430854831, `user_data` = 'a:8:{s:9:\"user_data\";s:0:\"\"' at line 1

UPDATE SET `last_activity` = 1430854831, `user_data` = 'a:8:{s:9:\"user_data\";s:0:\"\";s:10:\"id_cliente\";s:1:\"2\";s:4:\"name\";s:14:\"Martín Sosa\";s:8:\"lastName\";s:6:\"Plaz\";s:9:\"lastName2\";s:4:\"Loah\";s:15:\"numberExpedient\";s:5:\"00002\";s:5:\"email\";s:27:\"mart94@hotmail.com\";s:3:\"rol\";s:1:\"1\";}' WHERE `session_id` = '6b4cceb3679bdc63a4534c6be0efd54f'

Filename: libraries/Session.php

Line Number: 289

JPA/JPQL Query and Foreign Keys

I'm trying to run a query where I get specific Work done by a Customer based of their id. I'm having troubles making a queue with JPQL that will actually retrieve all the data based on the foreign key of the customerId

I've tried SELECT w FROM WorkEntry w WHERE w.customerId = 1 and that doesn't work. I'm wondering what I am missing? I'm fairly new to JPA and JPQL.

This is the customer class:

@Entity
@Table(name = "customer")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Customer.findAll", query = "SELECT c FROM Customer c"),
@NamedQuery(name = "Customer.findByCustomerId", query = "SELECT c FROM Customer c WHERE c.customerId = :customerId"),
@NamedQuery(name = "Customer.findByFirstName", query = "SELECT c FROM Customer c WHERE c.firstName = :firstName"),
@NamedQuery(name = "Customer.findByLastName", query = "SELECT c FROM Customer c WHERE c.lastName = :lastName"),
@NamedQuery(name = "Customer.findByStreetAddress", query = "SELECT c FROM Customer c WHERE c.streetAddress = :streetAddress"),
@NamedQuery(name = "Customer.findByCity", query = "SELECT c FROM Customer c WHERE c.city = :city"),
@NamedQuery(name = "Customer.findByState", query = "SELECT c FROM Customer c WHERE c.state = :state"),
@NamedQuery(name = "Customer.findByPostalCode", query = "SELECT c FROM Customer c WHERE c.postalCode = :postalCode"),
@NamedQuery(name = "Customer.findByPhoneNumber", query = "SELECT c FROM Customer c WHERE c.phoneNumber = :phoneNumber"),
@NamedQuery(name = "Customer.findByEmail", query = "SELECT c FROM Customer c WHERE c.email = :email")})
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "customer_id")
private Integer customerId;
@Size(max = 75)
@Column(name = "first_name")
private String firstName;
@Size(max = 75)
@Column(name = "last_name")
private String lastName;
@Size(max = 250)
@Column(name = "street_address")
private String streetAddress;
@Size(max = 50)
@Column(name = "city")
private String city;
@Size(max = 50)
@Column(name = "state")
private String state;
@Size(max = 45)
@Column(name = "postal_code")
private String postalCode;
@Size(max = 45)
@Column(name = "phone_number")
private String phoneNumber;
// @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
@Size(max = 250)
@Column(name = "email")
private String email;
@OneToMany(mappedBy = "customerId")
private Collection<ExpenseEntry> expenseEntryCollection;
@OneToMany(mappedBy = "customerId")
private Collection<WorkEntry> workEntryCollection;

public Customer() {
}

public Customer(Integer customerId, String firstName, String lastName, String streetAddress, String city, String state, String postalCode, String phoneNumber, String email) {
    this.customerId = customerId;
    this.firstName = firstName;
    this.lastName = lastName;
    this.streetAddress = streetAddress;
    this.city = city;
    this.state = state;
    this.postalCode = postalCode;
    this.phoneNumber = phoneNumber;
    this.email = email;
}

public Customer(String firstName, String lastName, String streetAddress, String city, String state, String postalCode, String phoneNumber, String email) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.streetAddress = streetAddress;
    this.city = city;
    this.state = state;
    this.postalCode = postalCode;
    this.phoneNumber = phoneNumber;
    this.email = email;
}


public Customer(Integer customerId) {
    this.customerId = customerId;
}

public Integer getCustomerId() {
    return customerId;
}

public void setCustomerId(Integer customerId) {
    this.customerId = customerId;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getStreetAddress() {
    return streetAddress;
}

public void setStreetAddress(String streetAddress) {
    this.streetAddress = streetAddress;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getState() {
    return state;
}

public void setState(String state) {
    this.state = state;
}

public String getPostalCode() {
    return postalCode;
}

public void setPostalCode(String postalCode) {
    this.postalCode = postalCode;
}

public String getPhoneNumber() {
    return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

@XmlTransient
public Collection<ExpenseEntry> getExpenseEntryCollection() {
    return expenseEntryCollection;
}

public void setExpenseEntryCollection(Collection<ExpenseEntry> expenseEntryCollection) {
    this.expenseEntryCollection = expenseEntryCollection;
}

@XmlTransient
public Collection<WorkEntry> getWorkEntryCollection() {
    return workEntryCollection;
}

public void setWorkEntryCollection(Collection<WorkEntry> workEntryCollection) {
    this.workEntryCollection = workEntryCollection;
}

@Override
public int hashCode() {
    int hash = 0;
    hash += (customerId != null ? customerId.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof Customer)) {
        return false;
    }
    Customer other = (Customer) object;
    if ((this.customerId == null && other.customerId != null) || (this.customerId != null && !this.customerId.equals(other.customerId))) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "consultant.billing.entity.Customer[ customerId=" + customerId + " ]";
}

}

And this is my WorkEntry class:

@Entity
@Table(name = "work_entry")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "WorkEntry.findAll", query = "SELECT w FROM WorkEntry w"),
@NamedQuery(name = "WorkEntry.findByWorkEntryId", query = "SELECT w FROM WorkEntry w WHERE w.workEntryId = :workEntryId"),
@NamedQuery(name = "WorkEntry.findByDate", query = "SELECT w FROM WorkEntry w WHERE w.date = :date"),
@NamedQuery(name = "WorkEntry.findByHoursWorked", query = "SELECT w FROM WorkEntry w WHERE w.hoursWorked = :hoursWorked")})
public class WorkEntry implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "work_entry_id")
private Integer workEntryId;
@Column(name = "date")
@Temporal(TemporalType.DATE)
private Date date;
// @Max(value=?)  @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "hours_worked")
private Double hoursWorked;
@JoinColumn(name = "activity_id", referencedColumnName = "activity_id")
@ManyToOne
private Activity activityId;
@JoinColumn(name = "customer_id", referencedColumnName = "customer_id")
@ManyToOne
private Customer customerId;

public WorkEntry() {
}

public WorkEntry(Date date, Double hoursWorked, Customer customerId, Activity activityId) {
    this.date = date;
    this.hoursWorked = hoursWorked;
    this.activityId = activityId;
    this.customerId = customerId;
}


public WorkEntry(Integer workEntryId) {
    this.workEntryId = workEntryId;
}

public Integer getWorkEntryId() {
    return workEntryId;
}

public void setWorkEntryId(Integer workEntryId) {
    this.workEntryId = workEntryId;
}

public Date getDate() {
    return date;
}

public void setDate(Date date) {
    this.date = date;
}

public Double getHoursWorked() {
    return hoursWorked;
}

public void setHoursWorked(Double hoursWorked) {
    this.hoursWorked = hoursWorked;
}

public Activity getActivityId() {
    return activityId;
}

public void setActivityId(Activity activityId) {
    this.activityId = activityId;
}

public Customer getCustomerId() {
    return customerId;
}

public void setCustomerId(Customer customerId) {
    this.customerId = customerId;
}

@Override
public int hashCode() {
    int hash = 0;
    hash += (workEntryId != null ? workEntryId.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof WorkEntry)) {
        return false;
    }
    WorkEntry other = (WorkEntry) object;
    if ((this.workEntryId == null && other.workEntryId != null) || (this.workEntryId != null && !this.workEntryId.equals(other.workEntryId))) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "consultant.billing.entity.WorkEntry[ workEntryId=" + workEntryId + " ]";
}

}

i have an issue with start date and end date?

It's about a resort where customer can book the room with start and end time mentioning.

for example: if ravi booked room no 106 from 2015-5-05 to 2015-5-20 and if rahul tries to book the same room from 2015-5-12 to 2015-5-17 .It should report a messagge but in my case the room is booked for rahul from 21-26(since the earlier days are booked already.)

I have to know how to compare the in between dates while insertion using mysql in php

sending form variables from a popup, to my database

I have a page with a popup, in that popup is a form and in that form I want to send the info to another page for processing and submission into my database. Right now my database gets filled with blank spaces where there should be a form variable, date and photo are the only two that insert correct variables. This is my popup form.

<div id="photo_form"> 
    <form id="photo_form" enctype="multipart/form-data" method="post" action="photo_system2.php">
        <input type="hidden" id="city" value="<?php echo $city; ?>">
        <input type="hidden" id="region" value="<?php echo $region; ?>">
        <input type="hidden" id="country" value="<?php echo $country; ?>">
        <input type="hidden" id="latitude" value="<?php echo $latitude; ?>">
        <input type="hidden" id="longitude" value="<?php echo $longitude; ?>">
        <textarea id="message" required type="text" placeholder="  enter message here:" onkeyup="restrict('email')" maxlength="300" style="height: 200px; width: 400px;"></textarea>
        <input id="name" required type="text" placeholder="  enter name:" onkeyup="restrict('email')" maxlength="50" style="width: 200px;">
        <input id="email" required type="email" placeholder="  enter email address:" onkeyup="restrict('email')" maxlength="88" style="width: 200px;">
        <input id="phone" placeholder="  phone number (optional):" onkeyup="restrict('email')" maxlength="88" style="width: 200px;">
        <input type="file" name="photo" accept="image/*">
        <br>select which subject:
        <div id="inquiry">
            <input checked='true' type="checkbox" id="inquiry[]" value="consult">free consultation<br>
            <input type="checkbox" id="inquiry[]" value="sell">sell<br>
        </div>
        <input type="submit" value="submit" >
    </form>
</div>

Photo_system2 looks like this

include_once("resources/init.php");
include_once("db_conx.php");
if (isset($_POST["message"]) && isset ($_POST["email"])){
$sql = "SELECT * FROM users";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$message = $_POST["message"];
$phone = $_POST["phone"];
$email = $_POST["email"];
$name = $_POST["name"];
$city = $_POST["city"];
$region = $_POST["region"];
$country = $_POST["country"];
$latitude = $_POST["latitude"];
$longitude = $_POST["longitude"];
$inq = $_POST['inquiry'];
    if ( isset($_POST['inquiry']) ) { 
$_POST['inquiry'] = implode(', ', $_POST['inquiry']);}
$_POST['inquiry'] = array();
$inq = implode(', ', (array)$inq);
$fileName = $_FILES["photo"]["name"];
$fileTmpLoc = $_FILES["photo"]["tmp_name"];
$fileType = $_FILES["photo"]["type"];
$fileSize = $_FILES["photo"]["size"];
$fileErrorMsg = $_FILES["photo"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
$db_file_name = date("DMjGisY")."".rand(1000,9999).".".$fileExt; // WedFeb272120452013RAND.jpg
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
    header("location: That image has no dimensions");
    exit(); 
}
if (!preg_match("/\.(gif|jpg|png|bmp|jpeg)$/i", $fileName) ) {
    header("location: your image file was not a recognized type (jpg, gif, bmp, jpeg, or png type");
    exit();
} else if ($fileErrorMsg == 1) {
    header("location:An unknown error occurred");
    exit();
}
$moveResult = move_uploaded_file($fileTmpLoc, "admin/photos/$db_file_name");     //edited
if ($moveResult != true) {
    header("location: File upload failed");
    exit();
}
include_once("image_resize.php");
$wmax = 2048;
$hmax = 2048;
if($width > $wmax || $height > $hmax){
    $target_file = "admin/photos/$db_file_name";                        //edited
    $resized_file = "admin/photos/$db_file_name";                             //edited
    img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
}
$sql = "INSERT INTO users(photo, username, message, phone, email, city, region, country, latitude, longitude, inquiry, inqdate) VALUES ('$db_file_name','$name','$message','$phone','$email','$city','$region','$country','$latitude','$longitude','$inq',now())";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
header('location: blog.php');
exit();
} 

Why am I getting blank spaces in my database where there should be these posted variables?

How to add a header to a file thats created by user input

So for my program to run it needs a certain type of file. This file is called a .fasta file. This type of file has a specific type of heading. It looks like this.

>gi|129295|sp|P01013|OVAX_CHICK GENE X PROTEIN (OVALBUMIN-RELATED)

My program gets text input from a user and puts it into a file. The problem that I have is that the file just contains the string from the user. My program can't read in just a string, the file needs to have that header on the first line and the string on the second line. Is there anyway to format a file so that the user input goes onto the second line?

Here is the html and php of when the user's input is changed into a file. So the text in the text box is created into a file but I need that header on the first line! Thanks in advance.

 <input id="BlastSearch" type="text" name="BlastSearch" value='' />

php

<?php
$sequence = $_POST['BlastSearch'];
$file = 'uploads/new.fasta';
$current = $sequence;
file_put_contents($file, $current);
?>

This creates a file with the text on the first line

So basically I need the header on the first line of the file and then the user input on the second line of the file. Thanks in advance!

Storing data MySQL in Kurdish font?

Hi so I've made an application in java that lets the user to store data in a MySQL database. Whenever I enter this به‌رواری ده‌رچوون I just get ??????. Is there any way I can fix that? It's really important that this job is done before tomorrow... I've never faced a problem such as this, and now I'm creating a database app for a company in Kurdistan, and now my friend asked, well does it store data with their characters? Heart attack! Please help!

I'm using PhpMyadmin on a localhost computer using XAMPP

Why do PHP & MySQL permit non-exact matches in SELECT queries?

Here's the story. I'm testing doing some security testing (using zaproxy) of a Laravel (PHP framework) application running with a MySQL database as the primary store for data.

Zaproxy is reporting a possible SQL injection for a POST request URL with the following payload:

id[]=3-2&enabled[]=on

Basically, it's an AJAX request to turn on/turn off a particular feature in a list. Zaproxy is fuzzing the request: where the id value is 3-2, there should be an integer - the id of the item to update.

The problem is that this request is working. It should fail, but the code is actually updating the item where id = 3.

I'm doing things the way I'm supposed to: the model is retrieved using Eloquent's Model::find($id) method, passing in the id value from the request (which, after a bit of investigation, was determined to be the string "3-2"). AFAIK, the Eloquent library should be executing the query by binding the ID value to a parameter.

I tried executing the query using Laravel's DB class with the following code:

$result = DB::select("SELECT * FROM table WHERE id=?;", array("3-2"));

and got the row for id = 3.

Then I tried executing the following query against my MySQL database:

SELECT * FROM table WHERE id='3-2';

and it did retrieve the row where id = 3. I also tried it with another value: "3abc". It looks like any value prefixed with a number will retrieve a row.

So ultimately, this appears to be a problem with MySQL. As far as I'm concerned, if I ask for a row where id = '3-2' and there is no row with that exact ID value, then I want it to return an empty set of results.

I have two questions:

  1. Is there a way to change this behaviour? It appears to be at the level of the database server, so is there anything in the database server configuration to prevent this kind of thing?

  2. This looks like a serious security issue to me. Zaproxy is able to inject some arbitrary value and make changes to my database. Admittedly, this is a fairly minor issue for my application, and the (probably) only values that would work will be values prefixed with a number, but still...

SQLite SELECT statement for column name where column has a value

What SQLite statement do I need to get the column name WHERE there is a value?

COLUMN NAME:   ALPHA BRAVO CHARLIE DELTA ECHO

ROW VALUE:                 0                  1            0          1         1

All I want in my return is: Bravo, Delta, Echo.

My SQL Max Connections error

I am working on a school project involving a MySQL database. We have encountered a problem where when we try to connect to our server we get the following error:

Severe:   Exception while deploying the app [FrienDB-Server]
Severe:   Exception during lifecycle processing
org.glassfish.deployment.common.DeploymentException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: User nwong already has more than 'max_user_connections' active connections

We are using our schools SQL server so we do not have access to changing the amount of max connections. I have tried killing connections on MySQL Workbench but that does not work. How can we fix this please help!

MySQL is there a chance of accidental offset of automatic increment

If inserting into two mysql tables at the same time is there a chance that another user could insert at the same time making the tables offset?

For example hypothetically: (In php)

$conn = new mysqli($servername, $username, $password, $dbname);

$sql = "INSERT INTO Name (user_id, name, email)
VALUES (DEFAULT, 'User name', 'john@example.com')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "INSERT INTO Location (user_id, addressline1, addressline1, postcode)
VALUES (DEFAULT, '123 street', 'anytown, country', '123456')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

If 'John' ran this at the same times as 'Bob' is it possible for john's Name to be given the auto-increment id of 1 and his Location to be given 2 because Bob's Location was given 1 first even though his Name was given 2.

Kinda hard to explain.

  • I want to know if 1000's if not millions of people are running this could it occur?
  • is there some reason MySQL will stop this from happening?
  • if not what can/can anything be done to prevent it?

Some mySQL statements only work after appending \g, other statements don't mind?

I'm trying to embrace mySQL commands in the raw form without using phpMyAdmin and I ran into this little issue so far...

I'm just wondering, I can connect to my db using wamp server and some commands won't work without typing \g after. For instance, I can connect, type my password and then immediately if I just try to create a database via:

CREATE DATABASE testing

It pushes me into a newline that looks like so:

mysql> CREATE DATABASE testing
    ->

1. How do I get back to a regular line to type after this happens? I keep having to close the command prompt and re initiate which is a hassle. 2. Why does it do this? Then when I type the following the command works just fine.

CREATE DATABASE testing \g

OK, now if that were the case I'd just understand and always type \g after everything because I know some things just "ARE" in programming. But then, I can type this line without the \g and it changes databases just fine.

USE firstdb

I haven't tested further on which commands do and don't work with/without the GO command but I thought I'd ask before I confuse myself a million times.

Much appreciated SO community! Thx in advance.

(Also, since I'm new to SO can someone please leave a comment on how to create those code snippets, but in the inline-block format so I don't have to always have to break my code references out onto new lines? Thanks!)

MySQL Like query not recognising anything but first word in database

Basically I am trying to use a $gen variable to match a user query to a string stored in a database describing a genre of music. My problem is that if the genre is Indie/Pop and the user selects Indie as a search query the event will display. If they select Pop the event does not display.

Here is how i am querying the database.

$sql="SELECT * FROM $tab WHERE genre LIKE '$gen%'AND dateForm = '$datepicker'";

Any help appreciated as ever

Laravel 4 Boolean in model

I have been trying to use a Boolean value in laravel TINYINT(1). However although it works fine for true/1 it cannot understand false/0. So if I change it to false it will still read as true as it seems Eloquent ignores the false value.

I have tried strings, ints and normal Boolean but they all have the same effect.

// I pull in the info kind of like this
$fields = Input::all();
$model->never_expires = $field['never_expires'];
$model->save();

never_expires is fillable within the model and uses a laravel boolean (created from the schema generator) which translates to a TINYINT(1).

I'm sure its something super simple I am missing, but I just can't see it.

Include blank values in array from foreach statement

I am using two mySQL tables to create a javascript chart. Table A:

id |   date   | attended
1  |2015-01-14| 3
2  |2015-01-20| 4
3  |2015-01-31| 2

Table B:

id | name |   date
1  | dog  |2015-01-14
2  | cat  |2015-01-14
3  | fish |2015-01-30

Using this code:

<?php
    $sql = "SELECT TableB.*
    FROM TableB
    RIGHT JOIN TableA
    ON TableB.date=TableA.date
    ORDER BY TableA.date";
    $names = $con->query($sql);
?>
var namegroup=[<?php
$info = array();
while($row=$names->fetch_assoc())  {
    $date = $row['date'];
    $name = $row['name'];
    $info[$date][] = $name;
}
foreach ($info as $date => $values) {
    echo '"';
    foreach($values as $value) {
        echo $value . ',';
    }
    echo '",';
}
?>];

I am able to look at Table A and get the rows in Table B whose dates are the same and following this answer was able do a foreach that provides me with this array:

var namegroup=[",","dog,cat,","fish,"]

The problem is that any blank data (which I want) is grouped at the beginning of the array and I want it to remain in an order based on the date to get an array like so:

var namegroup=["dog,cat,",",","fish,"]

Any help would be much appreciated. Also I am sure that my code is not perfect as I am somewhat teaching myself mySQL and PHP so if there are any suggestions for cleaner/better code feel free to weigh in. Thanks.

The connection variable in mysqlli_query is not defined

I have the following problem is that $con is not defined, despite i use it to connect to the database. I don't understand why is that.

<?php

    define("DB_HOST", "localhost");
    define("DB_NAME", "Bar_buddy_users");
    define("DB_USER", "local_server");
    define("DB_PASSWORD","010203");
    error_reporting( E_ALL );
    ini_set('display_errors', 1);
    $con = new mysqli(DB_HOST,DB_USER,"010203",DB_NAME) or die("Failed to connect to database");
    if ($con->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    echo "Connected successfully";
    function NewUser(){

        $first_name= $_POST["firstname"];
        $last_name = $_POST["lastname"];
        $email = $_POST["email"];
        $password = $_POST["password"];

        $query = "INSERT INTO Users (firstname, lastname, email, password) VALUES ('$first_name', '$last_name', '$email', '$password')";
        mysqli_query($con,$query);
        mysqli_close($con);


    }

    ?>

Are these SQL statements correct..?

I'm working on a sql project and I'm not sure if I'm answering the questions correctly. I don't have the schema or table with me at the moment and I just want a general critique on whether or not what I'm doing is correct.

QUESTIONS:

  1. List the first name, last name, sales rep ID, commission class, and commission rate for all Sales Reps. Concatenate the first and last names together. Sort by last name in ascending order, and use the following column headings: SalesRep_Name, Sales_Rep_ID, Commission_Class, Commission_Rate.

  2. List all rows and all columns from OrderDetail; sort by Order ID then by Product ID, both in ascending order; format the Product Price as currency.

  3. For all customers, list the customer ID, customer first name, customer last name, and customer phone number, along with the sales rep ID, sales rep first name, and sales rep last name of the sales rep to whom that customer belongs; sort by Customer ID in ascending order; format the phone number as ‘(###) ###-####’ by using concatenation and the SUBSTR function. Use the following column headings: CustID, CustFirstName, CustLastName, CustPhone, SalesRepID, SalesRepFirstName, SalesRepLastName.

  4. List the department ID, department name, sales rep ID, first name, last name, commission class, and commission rate of the sales rep(s) who earn the highest commission in each department. Use the following column headings: Dept_ID, Dept_Name, Sales_Rep_ID, First_Name, Last_Name, Commission_Class, Commission_Rate.

SQL statements:

--question 1

SELECT (SalesLName || ' , ' || SalesFName) AS SalesRep_Name, SalesRepID AS Sales_Rep_ID, salesR.Comm_Class AS Commission_Class, Comm_Rate AS Commission_Rate
FROM Sales_Report_exp salesR, Commission_exp Com
WHERE salesR.Comm_Class = Com.Comm_Class
ORDER BY salesR.SalesLName ;

--question 2

SELECT ORDT.OrderID AS Order_ID, Pro.ProdID AS ProductID,to_char(ProdPrice,'$99.99') AS ProductPrice
FROM Order_Detail_mys ORDT, Product_mys Pro
WHERE ORDT.ProdID = Pro.ProdID
ORDER BY ORDT.OrderID ASC, Pro.ProdID ASC;

--question 3

SELECT Cus.CustID AS CustID,CustFName AS CustFirstName,CustLName AS CustLastName,('(' || SUBSTR(Cus.CustPhone,1,3) || ')' || SUBSTR(Cus.CustPhone,4,3) || '-' || SUBSTR(Cus.CustPhone,7,4)) AS CustPhone,salesR.SalesRepID AS SalesRepID,SalesFName AS SalesRepFirstName,SalesLName AS SalesRepLastName
FROM Customer_mys Cus,Sales_Report_mys salesR
WHERE Cus.SalesRepID=salesR.SalesRepID
ORDER BY CustID;


--question 4

SELECT DeP.Dept_ID AS Dept_ID, Dept_Name AS Dept_Name, salesR.SalesRepID AS Sales_Rep_ID,         
      SalesFName AS First_Name, SalesLName AS Last_Name,
      CoM.Comm_Class AS Commission_Class , Comm_Rate AS Commission_Rate
FROM Department_mys DeP, Sales_Report_mys salesR, Commission_mys CoM
WHERE DeP.Dept_ID = salesR.Dept_ID AND CoM.Comm_Class = salesR.Comm_Class
      AND (DeP.Dept_ID,CoM.Comm_Rate) IN (SELECT DeP.Dept_ID,MAX(CoM.Comm_Rate) FROM Sales_Report_mys salesR, Commission_mys CoM, Department_mys DeP
                      WHERE CoM.Comm_Class = salesR.Comm_Class
                      AND DeP.Dept_ID = salesR.Dept_ID
                        GROUP BY DeP.Dept_ID);

2 Many to Many relationship - extract data with join

Please check the schema in the link below.

http://ift.tt/1JpkZl1

I want to select all properties and also the agent and the owner of each property. The problem is that both agent's and owner's details comes from the same table and there is a conflict.

What solution should i follow?

Note: Unfortunately I cannot change the db schema.

How to change data type when running query (not inside PHP)

Explanation

MySQL handles strings as Float and not Fixed for example if we have following column in database (amount type is DECIMAL(43,20))

+--------------------------+
|         amount           |
+--------------------------+
|  0.20000000000000000000  |
+--------------------------+

running the following PHP code

$amount_to_add = "0.1";
$stmt = $dbh->prepare("UPDATE table SET amount = amount + :amount");
$stmt->bindValue("amount", $amount_to_add);
$stmt->execute();

would result this:

+--------------------------+
|         amount           |
+--------------------------+
|  0.30000000000000004000  |
+--------------------------+

notice the additional 0.00000000000000004000

its because $amount_to_add was string

As i need to use BC Math function, its output is always string

And i can't turn it to double in PHP because it will lose precision and decimal points

Questions

How should i pass this to MySQL to treat it as fixed and not string (float) which doesn't need changing string type in PHP doesn't matter if we use mysql_query or pdo or mysqli or anything else

is something like declaring the amount type when running query possible? so it changes string to decimal inside mysql

MySQL table creation error #1005

Query:

CREATE TABLE location_share (
    id INT AUTO_INCREMENT PRIMARY KEY ,   
    user_id INT ,   
    circle_id INT ,   
    location_sharing_id  INT ,    
    CONSTRAINT fkuser1 FOREIGN KEY (user_id)
        REFERENCES user(id) ON DELETE CASCADE ON UPDATE CASCADE,    
    CONSTRAINT fkcircle1 FOREIGN KEY (circle_id)
        REFERENCES circle(id) ON DELETE CASCADE ON UPDATE CASCADE,    
    CONSTRAINT fksharing_policy FOREIGN KEY (location_sharing_id) 
        REFERENCES share(id) ON DELETE CASCADE ON UPDATE CASCADE  
) ENGINE = INNODB ; 

Error message:

error : #1005 - Can't create table '.\phonetracker\location_share.frm' (errno: 150)

Other tables:

CREATE TABLE user (
    id INT AUTO_INCREMENT PRIMARY KEY , 
    contact_no VARCHAR(25) UNIQUE NOT NULL, 
    email VARCHAR(50) UNIQUE NOT NULL, 
    first_name VARCHAR(25) NOT NULL , 
    last_name VARCHAR(25) , 
    device_id VARCHAR(250)NOT NULL , 
    image_path VARCHAR(180) , 
    password VARCHAR(30) NOT NULL , 
    latitude VARCHAR(18) , 
    longitude VARCHAR(18) 
) ENGINE=INNODB

CREATE TABLE circle (
    id INT AUTO_INCREMENT PRIMARY KEY , 
    name varchar(35)
) ENGINE=INNODB

CREATE TABLE share (
    id INT AUTO_INCREMENT PRIMARY KEY , 
    policy VARCHAR(6) UNIQUE NOT NULL 
)

MySQLi Equivalent Of MySQL Code

Can you give me the equivalent of this code im MySQLi? Can't get it right.

public function showTable($table) {
    if (mysql_num_rows(mysql_query("SHOW TABLES LIKE '" . DB_PREFIX . $table . "'"))) {
        return TRUE;
    } else {
        return FALSE;
    }
}

public function createTable() {
    $sql = "CREATE TABLE `" . DB_PREFIX . "category_related` (`category_id` INT(11) NOT NULL,   `rcategory_id` INT(11) NOT NULL, PRIMARY KEY (`category_id`, `rcategory_id`))";
    $this->db->query($sql);
}

How to get all columns that are used from various tables?

Lets say I have 10 tables (Table1 - Table10) and 10 columns in each table (lets say Column1 - Column10) - same column names across tables. I wanna find all columns in all tables that are not NULL for at least one row in that table and insert them into temp table for example @usedColumns that will be used later in the stored procedure.

What would be the fastest and most efficient way to do it assuming that you have millions of records in any or all of these tables? Current implementation uses UNPIVOT, but I'm trying to redesign that stored procedure since it's acting really slow. Or is UNPIVOT really the most efficient way?

One way I was thinking is to just check for if exists, but can't figure out how to put this into an efficient loop:

if exists (select top 1 1 from Table1 where Column1 is not null)
    insert into @usedColumns(table_name, column_name)
        values('Table1', 'Column1');

if exists (select top 1 1 from Table1 where Column2 is not null)
    insert into @usedColumns(table_name, column_name)
        values('Table1', 'Column2');
...

The DB in question is SQL Server, but I'm guessing the solution would work in MySQL and others too.

HTML/PHP Table Formatting

I'm very new to both HTML and PHP and I'm trying to get my table formatting right. I'm importing information from a database and it's all coming through correctly.

This is my code for my table

    echo "
    <tr>
    <td>".$row["id"]."</td>
    <td><center>".$row["firstname"]." ".$row["lastname"]."</center></td>
    <td><center>".$row["addr1"]."<br>".$row["addr2"]."<br>".$row["city"].",".$row["state"]." ".$row["zip"]."</center></td>
    <td>".$row["phone"]."</td>
    </tr>";

In my database, if a phone number was not entered it's saved as 0. Otherwise the number is saved as 5556667777. How can I format output in HTML so that my phone number is (555)-666-7777.

Also, the way I coded the address it should show up as

567 Main Street
Apt 4
New York, New York 88888

but if there's no information in the addr 2 (ie Apt 4) there's a blank space. Can I put a conditional inside html to remove this?

Querying in redis from node.js

I am coming from a traditional SQL background and am learning Redis. Specifically I am trying to run a redis database along with node.js

I have got the initial setup of redis done and tried out few of their basic commands. However I would like to create a database which has a Id, 3 marks of students, start date and end date.

I believe I can create an object which stores all the values for a particular ID (say obj) and use set function to save details regarding that ID.

client.set(ID, obj, function(err, reply) {
  console.log(reply);
});

If I call client.get(ID) , it will return the object which I saved above. However I would like to get values for the ID from a particular start date and end date. In SQL it would be like: SELECT * FROM TABLE WHERE StartDATE>='' and endDate='' and id= ID;

What would be the alternative in redis? I haven't been able to find any query example for redis in node.js

Also while inserting into the database, is inserting the object as a whole the best way to go about?

MYSQL joining subquery issue

I have one table that has people's grades in it.

+---------+--------+--------+--------+---------------------+
|  name   | grade1 | grade2 | grade3 |      datetime       |
+---------+--------+--------+--------+---------------------+
| person1 |     50 |     80 |    100 | 2015-05-05 12:00:00 |
| person1 |     60 |     43 |     88 | 2015-05-05 12:00:00 |
| person1 |     11 |     80 |     44 | 2015-05-05 12:00:00 |
| person1 |     64 |     75 |     37 | 2015-05-05 12:00:00 |
| person1 |     83 |     34 |     99 | 2015-05-05 12:00:00 |
| person2 |     45 |    100 |     95 | 2015-05-05 12:00:00 |
| person2 |     76 |     75 |     54 | 2015-05-05 12:00:00 |
| person2 |     68 |     53 |     66 | 2015-05-05 12:00:00 |
| person2 |     45 |     12 |     85 | 2015-05-05 12:00:00 |
| person2 |     75 |     78 |     55 | 2015-05-05 12:00:00 |
+---------+--------+--------+--------+---------------------+

What I need to do is pull a person's grades for a specific day and then a string representing their pass/fail report from previous (up to 7) days.

The final result I would be looking for based off the table would be something like this:

+---------------+---------+--------+--------+--------+----------------+
|    report     |  name   | grade1 | grade2 | grade3 |    datetime    |
+---------------+---------+--------+--------+--------+----------------+
| pass:3 fail:2 | person1 |     50 |     80 |    100 | 5/5/2015 12:00 |
| pass:2 fail:3 | person2 |     42 |    100 |     95 | 5/5/2015 12:00 |
+---------------+---------+--------+--------+--------+----------------+

So my sql to get the first part is pretty simple:

SELECT *
FROM Grades.grade_table gt
WHERE gt.datetime = '2015-05-05 12:00:00'

The second part of my query looks like this:

SELECT CONCAT('fail:',SUM(CASE WHEN pass_fail = 'fail' THEN 1 ELSE 0 END),' pass:',SUM(CASE WHEN pass_fail = 'pass' THEN 1 ELSE 0 END)) trend_data
FROM (
    SELECT
    CASE
        WHEN ((grade1+grade2+grade3)/3) >= 65 THEN 'pass'
        ELSE 'fail'
    END AS pass_fail
    FROM Grades.grade_table gt
    WHERE gt.name = 'person1'
    LIMIT 7
) trend_data

What I've tried:

SELECT 
(
  SELECT CONCAT('fail:',SUM(CASE WHEN pass_fail = 'fail' THEN 1 ELSE 0 END),' pass:',SUM(CASE WHEN pass_fail = 'pass' THEN 1 ELSE 0 END)) trend_data
  FROM (
    SELECT
    CASE
      WHEN ((grade1+grade2+grade3)/3) >= 65 THEN 'pass'
      ELSE 'fail'
    END AS pass_fail
    FROM Grades.grade_table gt
    WHERE gt.name = original_data.name
    LIMIT 7
  ) trend_data
) AS trending_data, original_data.*
FROM
(
  SELECT *
  FROM Grades.grade_table gt
  WHERE gt.datetime = '2015-05-05 12:00:00'
)

I keep getting cant find original_data.name in where clause, but I thought that would come through since it's in a separate select which is aliased.

mysql php Relate tables between (migrated) full tables

I'm having an issue relating tables. Long story short I'm migrating tables from a Postgres DB to a mysql one. Since I'm using Laravel, Eloquent has made it easy to migrate the tables "users" and "groups" because they are also objects, so all I did was convert the postgres result to Json, adding each element and saving it to the laravel's mysql DB. There's a many-to-many relationship between users and groups. Postgres also contains a "user-group" table with this relation. And I've managed to keep the same id's from postgres. But the code to save it to mysql is slightly different from before (saving users and groups). Here's what I'm doing:

foreach ($jsonData as $rel) {
    DB::table('group_user')->insert(array(
        array('user_id' => $rel['user_id']),
        array('group_id' => $rel['group_id']),
    ));
}

The DB format is pretty much the same in both databases. The only difference is that group_user has his own auto-incrementing id alongside with the foreign keys for user_id and group_id

Trying to run the function mentioned above turns this result.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a
child row: a foreign key constraint fails (`ProjectName`.`group_user`, 
CONSTRAINT `group_user_group_id_foreign` FOREIGN KEY (`group_id`) REFERENCES
`groups` (`id`)) (SQL: insert into `group_user` (`user_id`) values (1), (1))

I don't understand why, there's a user with id 1 and a group also with id 1. The table is fully functional in the postgres DB. My fear is that I'm establishing a relation with already existing data, and that might be what's causing these issues. Thank you for your time and patience.

EDIT: the corrected query goes like this btw

foreach ($jsonData as $rel) {
    DB::table('group_user')->insert(array(
        array('user_id' => $rel['user_id'], 'group_id' => $rel['group_id']),
    ));
}

Thank you very much @Mark B

How to find duplicate content and make the last entry the master id?

I'm having some issues with mysql and I hope you'll be able to help me. :)

This code is for simplifying search results on a library website. One book can be published many time but the content of the book remains the same. This is why only one book needs to appear when we search for "Ze Book" or one of its ISBNs.

Here is the table I have:

id | isbn    | bookname | disabled | alias
1  | A-B-C-D | Ze Book  | 0        |
2  | E-F-G-H | Ze Book  | 0        |
3  | I-J-K-L | Ze Book  | 0        |
4  | M-N-O-P | Bookeee  | 0        |
5  | Q-R-S-T | Bookeee  | 0        |

And this is what I would like to do for table:

id | isbn    | bookname | disabled | alias
1  | A-B-C-D | Ze Book  | 1        |
2  | E-F-G-H | Ze Book  | 1        |
3  | I-J-K-L | Ze Book  | 0        |A-B-C-D, E-F-G-H
4  | M-N-O-P | Bookeee  | 1        |
5  | Q-R-S-T | Bookeee  | 0        |M-N-O-P

I do not know where to begin exactly and especially if it could be done directly with mysql.

For the moment, I've managed to identify the duplicate book names:

SELECT bookname, COUNT(*) AS number
FROM table
GROUP BY bookname
HAVING COUNT(*) >1
ORDER BY number DESC

Any ideas what to do next?

Thank's a lot in advance, as you may have noticed, I'm still learning how to code. :)

cakephp 2.x using 'NOT IN' in subquery

I have this tiny mysql query(it returns element which dont have 1,3,5 state):

SELECT DISTINCT number FROM records WHERE number NOT IN
( SELECT number FROM records WHERE state_id = 1 or state_id = 3 or state_id = 5)

In cakephp i am not good at subquery but i was able to do it:

    $conditionsSubQuery['`Record2`.`state_id`'] = array(27,28,30);

      $db = $this->Record->State->getDataSource();

      $subQuery = $db->buildStatement(
    array(
        'fields'     => array('`Record2`.`number`'),
        'table'      => $db->fullTableName($this->Record),
        'alias'      => 'Record2',
        'limit'      => null,
        'offset'     => null,
        'joins'      => array(),
        'conditions' => $conditionsSubQuery,
        'order'      => null,
        'group'      => null
    ),
    $this->Record
);

      $subQuery = ' `Record`.`number` NOT IN (' . $subQuery . ') ';

      $subQueryExpression = $db->expression($subQuery);

     $conditions[] = $subQueryExpression;



     $subQuery=$this->Record->find('first', compact('conditions'),
             //array('recursive'=>0),
             array('fields'=>array('Record.state_id')
             ));

Maybe i don't understand something good but it is really annoying to get the same result takes tons of code,i know there is $this->query for core mysql But is there a way in the find to get the same result with just properly used 'conditions'? Or cakephp does not support 'NOT IN' and thats why no easier way?

Simple login error ERR_TOO_MANY_REDIRECTS

Im making a simple login for my adminpage. But I get the ERR_TOO_MANY_REDIRECTS error when I try to logg back in when I logged out. When I remove my cookies it works again so I think my logout file doenst remove the cookie correctly. I'm using chrome.

Login.php:

<?php 

//Connects to your Database 
mysql_connect("db location", "username", "password") or die(mysql_error()); 
mysql_select_db("database name") or die(mysql_error()); 

//Checks if there is a login cookie
if(isset($_COOKIE['ID_your_site'])){ //if there is, it logs you in and directes you to the members page
    $username = $_COOKIE['ID_your_site']; 
    $pass = $_COOKIE['Key_your_site'];
    $check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error());

    while($info = mysql_fetch_array( $check )){
        if ($pass != $info['password']){}
        else{
            header("Location: login.php");
        }
    }
 }

 //if the login form is submitted 
 if (isset($_POST['submit'])) {

    // makes sure they filled it in
    if(!$_POST['username']){
        die('You did not fill in a username.');
    }
    if(!$_POST['pass']){
        die('You did not fill in a password.');
    }

    // checks it against the database
    if (!get_magic_quotes_gpc()){
        $_POST['email'] = addslashes($_POST['email']);
    }

    $check = mysql_query("SELECT * FROM users WHERE username = '".$_POST['username']."'")or die(mysql_error());

 //Gives error if user dosen't exist
 $check2 = mysql_num_rows($check);
 if ($check2 == 0){
    die('That user does not exist in our database.<br /><br />If you think this is wrong <a href="login.php">try again</a>.');
}

while($info = mysql_fetch_array( $check )){
    $_POST['pass'] = stripslashes($_POST['pass']);
    $info['password'] = stripslashes($info['password']);
    $_POST['pass'] = md5($_POST['pass']);

    //gives error if the password is wrong
    if ($_POST['pass'] != $info['password']){
        die('Incorrect password, please <a href="login.php">try again</a>.');
    }

    else{ // if login is ok then we add a cookie 
        $_POST['username'] = stripslashes($_POST['username']); 
        $hour = time() + 3600; 
        setcookie(ID_your_site, $_POST['username'], $hour); 
        setcookie(Key_your_site, $_POST['pass'], $hour);     

        //then redirect them to the members area 
        header("Location: members.php"); 
    }
}
}
else{
// if they are not logged in 
?>

 <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> 

 <table border="0"> 

 <tr><td colspan=2><h1>Login</h1></td></tr> 

 <tr><td>Username:</td><td> 

 <input type="text" name="username" maxlength="40"> 

 </td></tr> 

 <tr><td>Password:</td><td> 

 <input type="password" name="pass" maxlength="50"> 

 </td></tr> 

 <tr><td colspan="2" align="right"> 

 <input type="submit" name="submit" value="Login"> 

 </td></tr> 

 </table> 

 </form> 

 <?php 
 }
 ?> 

Logout.php

<?php 
 $past = time() - 100; 
 //this makes the time in the past to destroy the cookie 
 setcookie(ID_my_site, gone, $past); 
 setcookie(Key_my_site, gone, $past); 
 header("Location: login.php"); 
 ?> 

members.php

<?php
//Connects to your Database 
mysql_connect("db location", "username", "password") or die(mysql_error()); 
mysql_select_db("database name") or die(mysql_error()); 

 //checks cookies to make sure they are logged in 
 if(isset($_COOKIE['ID_your_site'])){ 

    $username = $_COOKIE['ID_your_site']; 
    $pass = $_COOKIE['Key_your_site']; 
    $check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error()); 

    while($info = mysql_fetch_array( $check )){ 

        //if the cookie has the wrong password, they are taken to the login page 
        if ($pass != $info['password']){
            header("Location: login.php"); 
        }
        //otherwise they are shown the admin area
        else{

             echo "Admin Area<p>"; 
     echo "Your Content<p>"; 
     echo "<a href=logout.php>Logout</a>"; 
        }
    }
}

 else{ //if the cookie does not exist, they are taken to the login screen 
    header("Location: login"); 
 }
 ?>

Declare @ variable in SQL returning an error

I am trying to declare a variable in SQL. I Have tried both

declare @mean INT; set @mean = .5;

and

declare @mean INT set @mean = .5

I keep getting this error:

An unexpected token "" was found following "". Expected tokens may include: "declare @mean INT"

PHP - getting field name from column index using PDO

I'm looking for a way to get the field name from the column index returned by a SELECT query using PDO. What I'm looking for is an equivalent to

mysql_field_name(resource $result, int $field_offset)

The PHP documentation says the above function is deprecated as of PHP 5.5.0 and the alternative they suggest for PDO is considered experimental and the behavior of it may change without notice. That doesn't sound like something I would want in my application.

I also do not want to query the MySQL system tables to get the columns since that just would not be efficient.

If the results of the fetchAll() function returns the resulting array below, is there a way I can retrieve the value of the column name (which equals "NAME" below) by specifying the column index?

Array
(
[0] => Array
    (
        [NAME] => pear
        [0] => pear
        [COLOUR] => green
        [1] => green
    )

[1] => Array
    (
        [NAME] => watermelon
        [0] => watermelon
        [COLOUR] => pink
        [1] => pink
    )

)

i need to say in code if count(datefrom)and count(rooms) in rooms 1 (row where is said 1) >8 no more rooms [on hold]

i need to say in code if count(datefrom)and count(rooms) in rooms 1 (row where is said 1) >8

take look in image http://ift.tt/1GLcZb4

"stacking" mysql queries? multiple queries in millisecs each browser-refresh

I'm pretty new to socket.io and nodejs and at first I didn't even notice where the problem comes from until I 'console.log'ed nearly every function now.
I found out that refreshing the browser will "stack" up the console.log data and I assume also the mysql-queries I'm sending.

It's about a penny-auction website I'm building and I want to update every auction if there's a new bid or in another specific case. Every time this happens the auction-duration-time also increases. The client-side-javascript file keeps the connection to socket.io and updates the countdown timer when the price changes and stores the "new duration" that is left in seconds in an array that counts down to not constantly sending queries to the mysql database every second.

The main problem is: If the timer drops to 0, the client-side-file visually changes an auction to a "SOLD"-state, even if that's not the case server-side.
If you refresh your browser again, it's still counting down then.

If I restart my node server it works fine again. But I can't even image what will happen if multiple users refresh the website and will see the same not-intended behaviour. I also don't know how these "mulitple stacking" queries cause the problem to show the countdown counting to zero and doesn't reset the timer like it should be.

I've documented the bug in a video to show it to you more clearly: http://ift.tt/1EVRGqx

However there must be something wrong in my server.js-code, I guess. I can't figure out where exactly. I really hope anyone can help me somehow.

PS: The code structure comes from a nodejs-socket-io-mysql-tutorial: http://ift.tt/1lAN24d

SQL - Aggregate Function for DATEDIFF and WHERE/HAVING

I'm trying to query a DB to find the closest date to the parameter I passed in.

I have a problem I've been working on in IRC and lists for a while and can't find a solution. I'm using a python DBAPI (sqlalchemy) and am accessing the data both through CLI and a Flask App (but this should not impact the SQL). The database is MySQL with an InnoDB engine.

The query will depend on the a factor called target_expiration, but for which the value will frequently not exist in the DB. I need to find which value is nearest. For example, I will pass in target_date='2015-06-02' and would expect it to return to me both the 2015-06-03 result and the 2015-06-01 result that is one day away from my target_date.

Attempt at a solution:

SELECT * FROM table1 HAVING MIN(ABS(DATEDIFF(table1.Expiration, 
'2015-06-02'))) = ABS(DATEDIFF(table1.Expiration, '2015-06-02'));

This returns no rows. I can run the same MIN(ABS(DATEDIFF(...))) to return a scalar() and it succeeds and prints a value.

I tried using the HAVING function in order to use an aggregate function. I'm looking to scan the DB and find out what is my closest Expiration date to my target date. If it's zero, I'm done - I've found the date and I then just want to return all dates that match. If it's a day away, I don't know if it's a day forward or a day backwards (I'll deal with adding more functionality to choose later, but for now I'd just like to return all values that are n days away forwards or backwards).

Example Data: table1

This is an extremely limited sample of the data, in reality I have ~40 columns and billions of rows, so speed is a factor.

+------------+-------------+-------+
| Expiration | ProductType | Price |
+------------+-------------+-------+
| 2015-06-01 |      2      |   25  |
+------------+-------------+-------+
| 2015-06-03 |      1      |   22  |
+------------+-------------+-------+
| 2015-05-28 |      1      |   22  |
+------------+-------------+-------+
| 2015-05-28 |      2      |   28  |
+------------+-------------+-------+
| 2015-05-28 |      1      |   22  |
+------------+-------------+-------+
| 2015-06-04 |      2      |   28  |
+------------+-------------+-------+
| 2015-05-25 |      1      |   22  |
+------------+-------------+-------+
| 2015-05-25 |      2      |   28  |
+------------+-------------+-------+

Adding a constraint to both tables independently in join

I am trying to create a SELECT statement from two different tables, where I use to send messages, I don't want to send a message to someone for 1 wk after they join, however if I have already sent them a message I want to wait 10 days before sending next one.

Here's what I have:

SELECT c.*, g.resToMeeting, g.replied, g.conlevel, g.coffee, g.lastMessageSent 
FROM connections c
INNER JOIN groupmembers g
ON c.Id=g.Id 
AND g.groupN=244 # this decides the client I'm pulling for...(or group they own)
AND g.client=c.client
AND g.conlevel=1
AND (datediff(curdate(), g.lastMessageSent) > 10 OR datediff(curdate(), c.dateConnected) > 7)
AND c.validated=1 
AND c.process_rank=0 
ORDER BY c.dateAdded ASC
LIMIT 0, 200

The trouble I'm having is that it shows EITHER people who haven't joined within the last week, OR people who haven't received a messages within the last 10 days. It seems that it isn't working:

I received a record that had lastMessageSent as 2015-04-29, (which isn't 10 days ago) but the dateConnected was 2015-04-15 which was over 7 days. How can I enforce both rules "together" not either or, sometimes there is no data in lastMessageSent or dateConnected, and that should be OK.

Grid multi-checkbox bootstrap or similar

I need an approach. I'm new on web development. Sorry.

We need to show data from a mysql table on a grid-table.

We will use that grid to be able to select multiples rows and then update a column of the selected rows on the database.

I am testing bootstrap and looks nice but i don't know if it's enough for our problem.

Anyone could help us?

Regards

Create an Community Members List From MySQL

How to create an members list from the mysql table. I used this code an it gives me an white page.

<?php
 $sql = new mysqli('localhost','DB-USER','PASS','DB'); /

 $sql -> set_charset ( 'utf8' );
 if ($sql->connect_errno) {
    printf("Connect failed: %s\n", $sql->connect_error);
    exit();
 }

 while ($fetch = $profile_query_check->fetch (PDO::FETCH_ASSOC)) {
    if ($fetch == NULL OR $fetch["id"]) {
        break;
    }


    $username = $fetch['username'];
    $avatar = $fetch['avatar'];
    $id = $fetch['id'];

    //echo the profile info
}
 ?>

And this the user table

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(50) NOT NULL,
  `level` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `usertype` int(11) NOT NULL,
  `rpname` varchar(50) NOT NULL,
  `fbname` varchar(50) NOT NULL,
  `avatar` varchar(100) NOT NULL,
  `avatarchangedate` int(11) NOT NULL,
  `new_activity_count` int(11) NOT NULL,
  `online` tinyint(4) NOT NULL,
) ENGINE=MyISAM AUTO_INCREMENT=13397 DEFAULT CHARSET=utf8;

Please help me how to create the code? I'm noob

Update: But this whoisisonline code is working

<?php

if(!defined('A')){
  include "error.php";die(header('HTTP/1.0 403 Forbidden'));
}

global $sql;

//http://ift.tt/1GXGfOs
//Checks the sesson file to see how many files there are
function usersonline() {
    $sessionfiles = session_save_path() . "/sess*";

    $usersonline = count(glob($sessionfiles));

    return $usersonline;
}

if(isset(user::$current->id)){
    $current_ID = user::$current->id;
}else{
    $current_ID = "";
}

$sql->run("select_who_is_online", array(
    "userID" => $current_ID,
    "time" => (time() - 180)
));

// $sql->last_query_info();

$users = $sql->fetch_array();

$count = count($users);


$members_online = $count;

if (user::$loggedIn) {
    $members_online++;
}

$vistors_online = (usersonline() - $members_online);


//plural check
if ($members_online == 0)
    $members_online_message = "There are currently no NEETs online";
else if ($members_online == 1)
    $members_online_message = "There is currently only one NEET online";
else
    $members_online_message = "There are currently ".$members_online." NEETs online";

if($vistors_online == 1)
    $vistors_online_message = "and ".$vistors_online." Person passing by";
else
    $vistors_online_message = "and ".$vistors_online." People passing by";



echo "<div class='content_header blue small align_left' style='margin-top: 20px;'>Who is Online";
echo "<x style='float:right;margin-right:8px'>".$members_online_message.", ". $vistors_online_message ."<x>";
echo "</div>";

// echo "<h1 class='content_centered'>Who is Online</h1><br/>";
echo "<div class='content_padded content_centered content_feed light'>";
if($count){
    foreach($users as $user){
        // print_r($user);
        $user_obj = new user($user["id"]);
        $gUser = new gUser($user_obj);

        $tmp = '';
        $tmp .= "<div style='text-align: center; display: inline-block; width: 110px; margin-bottom: 10px;'>";
        // if ($friend->online)
        $tmp .= "<div class='basicSuccess' style='display: block; margin-bottom: 3px; width: 73px;'><i class='fa fa-wifi'></i> Online</div>";
        $tmp .= $gUser->htmlAvatar(70, "middle");
        $tmp .= "<div style='margin-top: 5px;'>" . $gUser->htmlSmall() . "</div>";
        $tmp .= "</div>";
        echo $tmp;
    }
}else if(user::$loggedIn){
    echo "<h5>No one else is online T^T</h5>";
}else {
    echo "<h5>No one is online T~T</h5>";
}


echo "</div>";

?>