-1

I'm developing a webaplicattion in php where there will be an area called 'My Products'. This area you can see the products that you listed. Lets say you placed a car to sell. You will have something like:

  • Model: R8
  • Color: Yellow
  • Brand: Audi
  • Type: Diesel
  • Price: 90000
  • CarID: 1

My problem: How can I select the carid so that I have the cardid as the key and the other values (eg. model, color, etc...) as values?

I'm using mysql to store the listings. SQL TABLE:

    +---------+------------------------------------------+------+-----+---------+----------------+
| Field   | Type                                     | Null | Key | Default | Extra          |
+---------+------------------------------------------+------+-----+---------+----------------+
| carid   | int(11)                                  | NO   | MUL | NULL    | auto_increment |
| brand   | enum('Alfa Romeo','Aston Martin','Audi') | NO   |     | NULL    |                |
| color   | varchar(20)                              | NO   |     | NULL    |                |
| type    | enum('gasoline','diesel','eletric')      | YES  |     | NULL    |                |
| price   | mediumint(8) unsigned                    | YES  |     | NULL    |                |
| mileage | mediumint(8) unsigned                    | YES  |     | NULL    |                |
| model   | text                                     | YES  |     | NULL    |                |
| year    | year(4)                                  | YES  |     | NULL    |                |
| user    | varchar(30)                              | YES  |     | NULL    |                |
+---------+------------------------------------------+------+-----+---------+----------------+

My pseudo code is something like this:

  1. Fetch ID of the cars that was listed by certain user;
  2. Use that ID as a key;
  3. Get every other options to be the values (diesel, yellow, etc...)

I have tried some codes since array_combine to foreach inside foreach. This is the code I have ended up so far:

$qry_id = "select carid from cars where user='$login'";
if ($car_id =  mysqli_query($link, $qry_id)){

    while ($row = mysqli_fetch_assoc($car_id)){
        //It will fetch the iD of the user in the DB
        $user_id = $row["carid"];

        $qry_model = "select model from cars where carid='$user_id'";
        if($model_obj = mysqli_query($link, $qry_model)){

            while ($row_2 = mysqli_fetch_assoc($model_obj)){

                $model = $row_2['model'];
                $final_array = array($user_id => $model);
            }
        }   

    }
}

I don't know if this is the right approach since it's my first webapp I'm building. I'm just using the model value in this code for the simplicity sakes.

Bruno Francisco
  • 3,841
  • 4
  • 31
  • 61
  • 1
    Why do you select data just for the purpose of re-selecting data? And in a *loop*? `SELECT * FROM cars WHERE user = ?` Or, if not `*`, the list of columns you need. Just get all the data you need in one query. (Also note you have a SQL injection vulnerability. You'll want to look into prepared statements with query parameters.) – David Jul 01 '16 at 19:19
  • What is `$value_user_id`? It is nowhere defined in your code. – trincot Jul 01 '16 at 19:22
  • @David I'll select everything but how do I use the values I need later on? In '$qry_model = "select model from cars where carid='$user_id'";' the value of `$valur_user_id` will change over every iteration, right? – Bruno Francisco Jul 01 '16 at 19:24
  • @trincot I have changed the code. I have copy/pasted from the previous code I was trying and forgot to change that variable. – Bruno Francisco Jul 01 '16 at 19:25
  • @JoaoTorres: It's not really clear what you mean or what you're trying to accomplish here. You call the same value by multiple names (Car ID and User ID), so what does it even mean? Ultimately, what data do you have when you get here and what data do you need from the database? – David Jul 01 '16 at 19:26
  • Check my answer, if your intention is to get an array with carId as key, then it will satisfy the purpose. – Dharam Jul 01 '16 at 19:27
  • Is `carid` a unique value in the `cars` table? – trincot Jul 01 '16 at 19:27
  • @trincot, I suppose it is as it seem to be an autoincrement column** – Dharam Jul 01 '16 at 19:29
  • @David My purpose: Having a page where you can see your articles. For that you will need the photos, the car model, the car color, etc... For that you need to get the carid (it's unique across the table), the color, the model, etc... Once I have all this data I will display them to the user. – Bruno Francisco Jul 01 '16 at 19:32
  • @JoaoTorres: So, you want every record in `cars` where `user = $login`? That's one query. I don't see why you're selecting just one column solely for the purpose of using it to select more columns from *the same rows*. – David Jul 01 '16 at 19:33
  • @David Exactly. I agree with you with just one query but the problem later on for me will be: How do I get the model, price, color, etc.. column? – Bruno Francisco Jul 01 '16 at 19:36
  • @JoaoTorres: They'd be in the results of that query. You already have code which uses a column from a query result, like this: `$row["carid"]` It's the same for any other column, just using the name of the column you want. – David Jul 01 '16 at 19:37
  • @David Ohhhh. You are right. I was completly blind. Would you mind answering the question so I could make your answer right? – Bruno Francisco Jul 01 '16 at 19:38

3 Answers3

2
$q = "SELECT * FROM cars where user=?";
if ($stmt =  $pdo->preapre($q)){
    $result=[];
    $stmt->execute([$login]);
    while ($row = $stmt->fetchObject()){
        $carId = $row->carid;
        unset($row->carid);
        $result[$carId]=$row;
    }
}   

now note that $pdo is object of pdo connecttion to the database not mysqli, you can do the same thing with mysqli but i am not uses to it

also i don't recommend that you use the user name on every column you should instead store the userId as foreign key to the primary key id in the table user

that will save alot more storage make the query faster ( it's easier to look for numbers than string ) and user can change it's name without having to change his name in all other tables ( userid won't be changing of course )

also carid should be unsigned int(10) not int(11) if wondering why 10 see that post MySQL datatype INT(11) whereas UNSIGNED INT(10)?

Community
  • 1
  • 1
Robert
  • 2,342
  • 2
  • 24
  • 41
1

You may do the following

Note this query is not safe and pron to SQL Injection, I would recommend to use prepared statements or PDO

The $carArray variable will finally have the array with carid as key in it

$query = "select * from cars where user='$login'";
$result = mysqli_query($query);
$carArray = array();
while ($row = mysqli_fetch_assoc($result)){
$carArray[$row['carid']] = $row;
}   
Dharam
  • 423
  • 2
  • 10
1

To avoid SQL injection, use prepared statements. You can use one query to fetch all attributes for the cars:

$qry_id = "select carid, model, price, color from cars where user=?";
$stmt = mysqli_prepare($link , $qry_d) or die("SQL statement error");
// Bind the login parameter to the statement
mysqli_stmt_bind_param($stmt, "s", $login);
mysqli_stmt_execute($stmt);
// bind every column in the SELECT
mysqli_stmt_bind_result($stmt, $user_id, $carid, $model, $price, $color);
while (mysqli_stmt_fetch($stmt)){
    $final_array[] = array(
        "model" => $model,
        "price" => $price,
        "color" => $color
    );
}
trincot
  • 317,000
  • 35
  • 244
  • 286
  • I still didn't quite get why the `$login` variable is doing at `mysqli_stmt_bind_param($stmt, "s", $login);`?! I have read the documentation from php website but still I haven't found the light. – Bruno Francisco Jul 02 '16 at 11:46
  • The SQL statement has a `?`, which indicates a parameter. The SQL engine can compile an SQL statement as such, but you still need to tell it what the value is for that parameter before it can give you the result. You do this with `mysqli_stmt_bind_param`. The `s` means your argument is of the string type. `$login` is the parameter value itself. This may seem more complicated than just inserting `$login` into the SQL string, but that is a bad habit, as it will make your code vulnerable to SQL injection. – trincot Jul 02 '16 at 11:52