mardi 28 juin 2016

Easy php issues connecting mysql [duplicate]

This question already has an answer here:

my connection php:

class ConnexionBDD{

    public function getConnexion(){

        try {
                $cnx= new PDO("mysql:host=localhost;dbname=portfolio",
                "root",
                "",
                    [   
                        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES 'UTF8'',
                        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
                    ]);
        }


        catch (Exception $e){

        die("Erreur de connexion à la base de donnée : ". $e->getMessage());
        }

        return $cnx;
    }


}

Error code :

Warning: PDO::__construct(): MySQL server has gone away in C:webPortfolioV_3.5controleurConnexionBDD.php on line 15

Warning: PDO::__construct(): Error while reading greeting packet. PID=6980 in C:webPortfolioV_3.5controleurConnexionBDD.php on line 15

Warning: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2006] MySQL server has gone away' in C:webPortfolioV_3.5controleurConnexionBDD.php:15 Stack trace: #0 C:webPortfolioV_3.5controleurConnexionBDD.php(15): PDO->__construct('mysql:host=loca...', 'root', '', Array) #1 C:webPortfolioV_3.5controleurinsertionBDD.php(10): ConnexionBDD->getConnexion() #2 C:webPortfolioV_3.5controleurContactController.php(15): insertionBDD->createClient('coudoumie', 'morgan', '', '') #3 C:webPortfolioV_3.5index.php(35): ContactController->Contact() #4 {main} thrown in C:webPortfolioV_3.5controleurConnexionBDD.php on line 15

Fatal error: Maximum execution time of 30 seconds exceeded in C:webPortfolioV_3.5controleurConnexionBDD.php on line 15

DBAL cardinality violation error

I am getting the 'Cardinality Violation' error, for the following SQL:

DoctrineDBALExceptionDriverException: An exception occurred while executing

SELECT p.* FROM mod_products_products p 
LEFT JOIN mod_products_products_categories c_link ON c_link.product_id = p.id 
LEFT JOIN mod_products_brands b ON p.brand_id = b.id 
LEFT JOIN mod_products_groups vg ON p.variation_id = vg.id 
LEFT JOIN mod_products_categories c ON c_link.category_id = c.id 
LEFT JOIN mod_products_group_options vg_o ON vg_o.group_id = vg.id 
LEFT JOIN mod_products_group_values vg_o_v ON vg_o_v.option_id = vg_o.id 
WHERE (p.name LIKE (?, ?)) AND (p.parent_id = 0) AND (vg_o.disabled=0) 
GROUP BY p.id ORDER BY p.name ASC 
LIMIT 18446744073709551615 OFFSET 0

with params ["%big%", "%light%"]: SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s).

The error only occurs if there is more than one value defined in the parameter list for WHERE (p.name LIKE (?, ?)).

I am using executeQuery(), and passing the array as Connection::PARAM_STR_ARRAY. In the original statement I am defining the trouble point as:

$builder->andWhere('p.name LIKE (:partial_names)');

It seems it doesn't like getting an array passed as partial_names. Any ideas on what is causing this, and how to avoid it?

Admin panel in php

I am struggling with redirecting to a admin panel page in php. I have tried 2 different codes without success. I have no idea what I am doing, as I don't have a good solid understanding of the fundamentals of php. But I think I'm getting close, any help appreciated. Thankyou in advance.

user_level is the entry in the database , 2 is for members and 3 for admin. error logs posted at the bottom.

  $username = $_SESSION['username'];
            while($row = mysqli_fetch_object($conn))
            {
                $admin = $row->user_level;

        }
        if ($admin == 3) { header('Location: admin.php'); 

    }

code 2

$username = $_SESSION['username'];
$query_level = mysqli_query("SELECT user_level FROM members WHERE username = '$username' ");
$run_level = mysqli_fetch_array($conn, $query_level);
$row = mysqli_fetch_assoc($run_level);
    if ($row == 3) {
        header('Location: admin.php');
    } 

[26-Jun-2016 09:03:09 Australia/Brisbane] PHP Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, object given in /public_html/login/memberpage.php on line 46 [26-Jun-2016 09:03:09 Australia/Brisbane] PHP Notice: Undefined variable: admin in /public_html/login/memberpage.php on line 51

26-Jun-2016 09:05:06 Australia/Brisbane] PHP Warning: mysqli_query() expects at least 2 parameters, 1 given in /public_html/login/memberpage.php on line 46 [26-Jun-2016 09:05:06 Australia/Brisbane] PHP Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /public_html/login/memberpage.php on line 47 [26-Jun-2016 09:05:06 Australia/Brisbane] PHP Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in /public_html/login/memberpage.php on line 48

Fetching two matches in a MySQL query?

So I have some code I'm trying to figure out... I have two tables:

TABLE: matches

event_id
match_id (primary)
match_score
match_p1
match_p2
match_win

TABLE: results

event_id
user_id
result_id (primary)
result_name
result_extra

The weird thing about the data is the content of of the matches table actually links to the results table in multiple fashions.

There will be an integer in match_p1 and match_p2 that link to the results_extra field on the results table. This is designed because each match has two players in it (p1 and p2), and each player has one result for each event.

If I wanted to get a list of all matches in an event, I would do the following:

SELECT *
FROM matches
WHERE event_id = 324

If I wanted to get a list of all matches belonging to a single player, I would do:

SELECT matches.*
FROM matches
    LEFT JOIN results
        ON ((results.result_extra = matches.match_p1) OR
            (results.result_extra = matches.match_p2))
WHERE results.user_id = 1566

However, this is where things get a bit complicated... What if I wanted to get a list of matches where player 1566 fought player 2058? Its the logic for this query I can't figure out. Could you guys help me out?

C# loading images and strings into one DataGridView/ListView using sql query

Hi guys I'm creating this messenger and I would like a List View or DataGridView which shows the users friend's avatar and name. It works perfectly in a list box but I cannot add images.

List box Code:

            var query = from o in Globals.DB.Friends
                    where o.UserEmail == Properties.Settings.Default.Email
                    select new
                    {
                        FirstName = o.FirstName,
                        LastName = o.LastName,
                        Email = o.Email,
                        Display = string.Format("{0} {1} - ({2})", o.FirstName, o.LastName, o.Email)
                    };
        FriendsLb.DataSource = query.ToList();
        FriendsLb.ClearSelected();

List box display and value members:

            FriendsLb.DisplayMember = "Display";
        FriendsLb.ValueMember = "Email";
        FriendsLb.ValueMember = "FirstName";
        FriendsLb.ValueMember = "LastName";

        Globals.DB.Friends.Clear();
        Globals.DB._UserDetails.Clear();
        Globals.DB.AcceptChanges();

        string friends = string.Format("{0}\Friends\" + Properties.Settings.Default.Email + ".dat", Application.StartupPath);
        if (File.Exists(friends))
            Globals.DB.Friends.ReadXml(friends);

        string user = string.Format("{0}\Users\" + Properties.Settings.Default.Email + ".dat", Application.StartupPath);
        if (File.Exists(user))
            Globals.DB._UserDetails.ReadXml(user);

        FriendsLb.ClearSelected();

DataGridView Code:

            var query = from o in Globals.DB.Friends
                    where o.UserEmail == Properties.Settings.Default.Email
                    select new
                    {
                        FirstName = o.FirstName,
                        LastName = o.LastName,
                        Email = o.Email,
                        Avatar = o.Avatar,
                        Display = o.Avatar + string.Format("{0} {1} - ({2})", o.FirstName, o.LastName, o.Email)
                    };
        FriendsDGV.DataSource = query.ToList();

Problem is: DataGridView doesn't provide display and value members which is needed to load the data.

List View: Doesn't provide data source or display and member values

How can I do this? :(

QueryOver - adding additional criteria to a Join

I'm quite new to NHibernate and QueryOver and I can't get NHibernate to generate the SQL I need.

I need to make a join and have an extra criteria on so I avoid getting to much data from the table I'm joining with.

The SQL I receive from QueryOver is:

SELECT * FROM adresse this_ 
left outer join r580_test.afvigelse remarkalia1_ on this_.id=remarkalia1_.adrid 
left outer join r580_test.afvigelseklagepunkter remarkcomp5_ on remarkalia1_.id=remarkcomp5_.afvigelseid 
left outer join r580_test.klagepunkter complainta2_ on remarkcomp5_.klagepunktid=complainta2_.id 
WHERE  this_.id = 16633 and remarkalia1_.dato between '2009-03-13 00:00:00' and '02-03-2012 16:34:35'

What I would like is this(the where date between has been moved to the end for the first left outer join):

SELECT * FROM adresse this_ 
left outer join r580_test.afvigelse remarkalia1_ on this_.id=remarkalia1_.adrid and remarkalia1_.dato between '2009-03-13 00:00:00' and '02-03-2012 16:34:35'
left outer join r580_test.afvigelseklagepunkter remarkcomp5_ on remarkalia1_.id=remarkcomp5_.afvigelseid 
left outer join r580_test.klagepunkter complainta2_ on remarkcomp5_.klagepunktid=complainta2_.id 
WHERE  this_.id = 16633

My QueryOver looks like this:

adr = session.QueryOver<Address>()
    .Where(x => x.Id == 16633)
    .JoinQueryOver<Remark>(y => y.Remarks).Where(y => y.Created > DateTime.Now.AddDays(-14))
    .JoinAlias(y => y.RemarkComplaint, () => complaintAlias, JoinType.LeftOuterJoin)
    .SingleOrDefault();

Anyone got an idea about how to fix this?

Best way to show friends of a user in alphabetical order

On a social network I am working on in PHP/MySQL, I have a friends page, it will show all friends a user has, like most networks do. I have a friend table in MySQL, it only has a few fields. auto_ID, from_user_ID, to_friend_ID, date

I would like to make the friends page have a few different options for sorting the results,

  1. By auto_ID which is basically in the order a friend was added. It is just an auto increment id

  2. new friends by date, will use the date field

  3. By friends name, will have a list in alphabetical order.

The alphabetical is where I need some advice. I will have a list of the alphabet A-Z, when a user clicks on K it will show all the user's name starting with K and so on. The trick is it needs to be fast so doing a JOIN on the user's table is not an option, even though most will argue it is fast, it is not the performance I want for this action. One idea I had is to add an extra field to my friendship table and store the first letter of the users name in it. User's can change there name at anytime so I would have to make sure this is updated on possible thousands of records, anytime a user changes there name.

Is there a better way to do this?