-1

I get this two arrays successfully from a post form and I am able to print_r both of it, now is time to insert it. That's the order I wanted it, but it doesn't update my database, it upload the files, and it doesn't return any errors.

What is wrong with my PDO?

Adding_a_car.php

<form action="" method="post" enctype="multipart/form-data">

    <ul>

            <li>
                Year:<br>
                <input type="text" name="year">
            </li>
            <li>
                Make:<br>
                <input type="text" name="make">
            </li>
            <li>
                Model:<br>
                <input type="text" name="model">
            </li>
            <li>
                Engine:<br>
                <input type="text" name="engine">
            </li>
            <li>
                Sound System:<br>
                <input type="text" name="sound_system">
            </li>           
            <li>
                Mileage:<br>
                <input type="text" name="mileage">
            </li>           
            <li>
                Attribute 1:<br>
                <input type="text" name="att1">
            </li>           
            <li>
                Attribute 2:<br>
                <input type="text" name="att2">
            </li>           
            <li>
                Attribute 3:<br>
                <input type="text" name="att3">
            </li>           
            <li>
                Attribute  4:<br>
                <input type="text" name="att4">
            </li>           
            <li>
                Attribute 5:<br>
                <input type="text" name="att5">
            </li>           
            <li>
                Attribute 6:<br>
                <input type="text" name="att6">
            </li>   
            <li>
                Attribute 7:<br>
                <input type="text" name="att7">
            </li>           
            <li>
                Attribute 8:<br>
                <input type="text" name="att8">
            </li>           
            <li>
                Attribute 9:<br>
                <input type="text" name="att9">
            </li>
            <li>
                Attribute 10:<br>
                <input type="text" name="att10">
            </li>           
            <li>
                Attribute 11:<br>
                <input type="text" name="att11">
            </li>           
            <li>
                Attribute 12:<br>
                <input type="text" name="att12">
            </li>   
            <li>
                Attribute 13:<br>
                <input type="text" name="att13">
            </li>   
            <li>
                Attribute 14:<br>
                <input type="text" name="att14">
            </li>   
            <li>
                Attribute 15:<br>
                <input type="text" name="att15">
            </li>

                <li>Image1: <input name="image[]" type="file" /><br /></li>
                <li>Image2: <input name="image[]" type="file" /><br /></li>
                <li>Image3: <input name="image[]" type="file" /><br /></li>
                <li>Image4: <input name="image[]" type="file" /><br /></li>
                <li>Image5: <input name="image[]" type="file" /><br /></li>
                <li>Image6: <input name="image[]" type="file" /><br /></li>
                <li>Image7: <input name="image[]" type="file" /><br /></li>
                <li>Image8: <input name="image[]" type="file" /><br /></li>
                <li>Image9: <input name="image[]" type="file" /><br /></li>
                <li>Image10: <input name="image[]" type="file" /><br /></li>
                <li>Image11: <input name="image[]" type="file" /><br /></li>
                <li>Image12: <input name="image[]" type="file" /><br /></li>


                <li><input type="submit" value="Upload" /></li>



    </ul>

</form>
<?php 
if (isset($_POST))
{

                $vehicleinfo = array
                (
                'year'          => $_POST['year'],
                'make'          => $_POST['make'],
                'model'         => $_POST['model'],
                'engine'        => $_POST['engine'],
                'sound_system'  => $_POST['sound_system'],
                'mileage'       => $_POST['mileage'],
                'att1'          => $_POST['att1'],
                'att2'          => $_POST['att2'],
                'att3'          => $_POST['att3'],
                'att4'          => $_POST['att4'],
                'att5'          => $_POST['att5'],
                'att6'          => $_POST['att6'],
                'att7'          => $_POST['att7'],
                'att8'          => $_POST['att8'],
                'att9'          => $_POST['att9'],
                'att10'         => $_POST['att10'],
                'att11'         => $_POST['att11'],
                'att12'         => $_POST['att12'],
                'att13'         => $_POST['att13'],
                'att14'         => $_POST['att14'],
                'att15'         => $_POST['att15']


                );



    error_reporting(E_ALL);

    $success = 0;
    $picturepaths[12];
    $ii = 0;
    $fail = 0;
    $pictureid = 1;
    $i = 1;
    $uploads_dir = 'images';
    $count = rand(5, 70000);
    foreach ($_FILES["image"]["error"] as $key => $error) {
        if ($error == UPLOAD_ERR_OK) {

            $tmp_name = $_FILES["image"]["tmp_name"][$key];
            $name = $_FILES["image"]["name"][$key];
            $uploadfile = "$uploads_dir/$name";
            $ext = strtolower(substr($uploadfile,strlen($uploadfile)-3,3));
            if (preg_match("/(jpg|gif|png|bmp)/",$ext)){

                $newfile = "$uploads_dir/picture".str_pad($count++,2,'0',STR_PAD_LEFT).".".$ext;


                if(move_uploaded_file($tmp_name, $newfile)){
                    $success++;
                    $picturepaths[] = $newfile;
                    $ii++;


                }else{
                    echo "Couldn't move file: Error Uploading the file. Retry after sometime.\n";
                    $fail++;
                }
            }else{
                echo "Invalid Extension.\n";
                $fail++;
            }
        }
    }
}
echo "<br> Number of files Uploaded:".$success;
echo "<br> Number of files Failed:".$fail;
//print_r($picturepaths);
//print_r($vehicleinfo);

add_a_car($picturepaths, $vehicleinfo);

function add_a_car();

function add_a_car($picturepaths, $vehicleinfo)
{
    //$paths[12];
    //$info[21];
    $iii = 1;
    $paths = array // here we import the picture unorganized and organize them
    (
        'picture1'  => '',
        'picture2'  => '',
        'picture3'  => '',
        'picture4'  => '',
        'picture5'  => '',
        'picture6'  => '',
        'picture7'  => '',
        'picture8'  => '',
        'picture9'  => '',
        'picture10' => '',
        'picture11' => '',
        'picture12' => ''
    );
    foreach($picturepaths as $field=>$data)
    {

        $paths['picture'.$iii] = '\''.$data.'\', ';

        $iii++;
    }
    foreach($vehicleinfo as $field=>$data)
    {

        $info[] = '\''.$data.'\', ';


    }

    //i have both arrays working fully according and not missing info total of 33 

    $sql = "INSERT INTO auto(year, make, model, engine, sound_system, mileage, att1, att2,
    att3, att4, att5, att6, att7, att8, att9, att10, att11, att12, att13, att14, att15, picture1,
    picture2, picture3, picture4, picture5, picture6, picture7, picture8, picture9,
    picture10, picture11, picture12) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    print_r($paths);
    print_r($vehicleinfo);


    $sth = $dbh->prepare($sql);
    $sth->execute($final);

}

Results for print_r($vehicleinfo) print_r($paths)

Notice: Undefined variable: info in C:\xampp\htdocs\cardealerwins\core\functions\users.php on line 5
Array ( [year] => 19154 [make] => cehedcad [model] => asdfasd [engine] => 454 [sound_system] => [mileage] => [att1] => [att2] => fas [att3] => [att4] => [att5] => [att6] => asdfa [att7] => sdfasdfas [att8] => [att9] => [att10] => [att11] => dfasdfa [att12] => dfas [att13] => [att14] => [att15] => ) Array ( [picture1] => 'images/picture26351.png', [picture2] => 'images/picture26352.png', [picture3] => 'images/picture26353.png', [picture4] => [picture5] => [picture6] => [picture7] => [picture8] => [picture9] => [picture10] => [picture11] => [picture12] => ) 
Notice: Undefined variable: dbh in C:\xampp\htdocs\cardealerwins\core\functions\users.php on line 48

Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\cardealerwins\core\functions\users.php on line 48

i cant get pdo to give me errors trying this

$dsn = 'mysql:dbname=cardealerwins;host=127.0.0.1';
    $user = 'root';
    $password = '';
    $dbh = new PDO($dsn, $user, $password);

    $sth = $dbh->prepare($sql);
    $sth->execute($final);
    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

connection.php and new updates for pdo

<?php
$connect_error = 'sorry we\'re expierencing connection problems.';
mysql_connect('localhost', 'root', '') or die($connect_error);
mysql_select_db('cardealerwins') or die($connect_error);


$dsn = 'mysql:dbname=cardealerwins;host=127.0.0.1';
$user = 'root';
$password = '';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}



?>


    $dbh->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
    $sth = $dbh->prepare($sql);
    $sth->execute($final);
    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    print_r($sth->errorInfo());
sdf asdfad
  • 21
  • 1
  • 6
  • 3
    lol i fixed it sorry, – sdf asdfad Jun 26 '13 at 03:12
  • Have you verified that `$final[0]` contains precisely the number of elements that your statement expects? – George Cummins Jun 26 '13 at 03:14
  • Use pdo error handler to know if it spit out any errors, see http://stackoverflow.com/a/3999871/342740 – Prix Jun 26 '13 at 03:15
  • i changed `$paths[12]` and `$info[21]` = 33 arguments = expected statements and still nothing, how can i test pdo insertion right away? – sdf asdfad Jun 26 '13 at 03:17
  • i tried but get `Using $this when not in object context` @Prix – sdf asdfad Jun 26 '13 at 03:19
  • @sdfasdfad you have to change the variable name `$this` to the name you're using on your PDO connection variable name... also if u can post a `print_r` of `$final` would help. – Prix Jun 26 '13 at 03:20
  • In your case `$this` should be `$dbh` and be after your line with `$dbh` – Prix Jun 26 '13 at 03:21
  • okay i updated the size of each array before hand, i dont know if i did it right and then i added an actual result of print_r @Prix – sdf asdfad Jun 26 '13 at 03:28
  • You see at your $final you have 2 inner arrays and not only 1 so when you do $final[0] you are only trying to insert the initial 18 entries from the first inner array and not the total from both arrays. So the 6 pictures are left out and you have a total of 24 items. – Prix Jun 26 '13 at 03:28
  • i dont understand why my arrays are not respecting my field numbering, say i dont enter miles well now one of the specified attributes will be att1 so mileage will be stored in att1,, also i cant get pdo to even show errors, mind teamviewer for a few minutes please @Prix – sdf asdfad Jun 26 '13 at 03:39
  • @sdfasdfad can you do a print_r on $picturepaths and $vehicleinfo ? You might be doing some huge unneeded mess there. Are you receiving the data from a form ? – Prix Jun 26 '13 at 03:42
  • yes i can thanks for your time man , ive been stressing this for days now @Prix – sdf asdfad Jun 26 '13 at 03:47
  • @sdfasdfad ok so from what I see on your form you have total of 30 fields where not all of the 12 images fields will be always filled and where not all of your 12 attributes will be always filled is that correct ? You were saying 33 early. – Prix Jun 26 '13 at 04:07
  • 1
    -1 for the table structure, which is obviously wrong. – Your Common Sense Jun 26 '13 at 05:09
  • @YourCommonSense can't agree more with you – Prix Jun 26 '13 at 05:14
  • @YourCommonSense i fixed all of that look at my new code, two arrays match 33 values for 33 inputs on database auto and are in order to match each, so how is my table structure so wrong? u downgraded my self esteem man :( – sdf asdfad Jun 26 '13 at 05:15
  • @sdfasdfad table structure as in your database tables, like you could have a separated table for your images alone, that are linked with the car key instead of having 12 columns for images and same goes for attributes of course that is just an example of what you could have done. – Prix Jun 26 '13 at 05:18

1 Answers1

0

Since you are hard coding a KEY to each of your fields that are named after your table structure, you could do it like this:

function add_a_car($picturepaths, $vehicleinfo)
{
    // we do this so we can inherit the connection 
    // from the connect.php
    global $dbh;

    // count the total needed of placeholders for the query
    $total = count($vehicleinfo) + count($images);

    // create all the placeholders
    $input_list = substr(str_repeat(',?', $total), 1);

    // create the fields list in the same order of your array
    $fields = implode(", ", array_keys($vehicleinfo));

    // since for the pictures you don't have a key we need 
    // to create the field names for it based on the amount of pictures
    for ($i = 1; $i <= count($images); $i++)
    {
        $fields .= ',picture' . $i;
    }

    // now we merge the 2 arrays into 1    
    $final = array_merge($vehicleinfo,$images);

    // here is your new SQL query
    $sql = "INSERT INTO auto ($fields) VALUES ($input_list)";

    $sth = $dbh->prepare($sql);
    $sth->execute($final);
    print_r($sth->errorInfo());
}

I am not entirely sure if PDO will take only the array values or it must be an array with only values but if the later you can change the $final to:

$final = array_merge(array_values($vehicleinfo),array_values($images));

This is how your connect.php should look like:

<?php
$connect_error = 'sorry we\'re expierencing connection problems.';
$dsn = 'mysql:dbname=cardealerwins;host=127.0.0.1';
$user = 'root';
$password = '';

try
{
    $dbh = new PDO($dsn, $user, $password);
    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $e)
{
    echo 'Connection failed: ' . $e->getMessage();
}
Prix
  • 19,417
  • 15
  • 73
  • 132
  • wow thanks alot @Prix but i modified this code to work by giving my a complete list of keys for each, so at the end i get 33 keys no matter what, vehicle info first then vehicle pictures just like in my sql see my update and still pdo not working im gonna try the error now but the arrays issues is resolved thanks alot man i really appreciate it with all my heart – sdf asdfad Jun 26 '13 at 04:44
  • @sdfasdfad drop me another comment once you update it and I will come check. – Prix Jun 26 '13 at 04:45
  • now :) i hope i can finally start sending this to the mysql, im ready with a complete string, 32 keys, now to convert it to msql insertion, i need you man, you gotta work out my code, just tell me what to look for to do this :) god be with u – sdf asdfad Jun 26 '13 at 04:50
  • @sdfasdfad ok, your code is a bit confusing now, it seems you have initiated your database connection on one file and is trying to reuse it on a second file, I don't know if they are classes or direct calls but I can tell that the issue of your update is telling me your function does not know what `$dbh` is. To put it simple, where is your `$dbh = new PDO` line ? in what file ? is it inside a class ? where are u using it ? are u using include to include your files on adding_a_car.php file ? – Prix Jun 26 '13 at 04:57
  • @sdfasdfad you can also remove `$info[21];` as you have it as `$info[]` inside your `foreach`. – Prix Jun 26 '13 at 05:00
  • i have that in my connect.php that gets included in the top, to fix this, check my update, i declared the pdo on the same spot, still nothing, i can do a normal mysql insertion, but pdo wont go through, let me change ip to localhost see waht happens @Prix – sdf asdfad Jun 26 '13 at 05:02
  • @sdfasdfad then inside your function add at the top first line after `function add_a_car($picturepaths, $vehicleinfo) {` the follow `global $dbh;` – Prix Jun 26 '13 at 05:03
  • @sdfasdfad after you do that, update your question with how your code is now, and how your connect.php is just the first 2 lines of your connect php starting from the `$dbh = new PDO` line – Prix Jun 26 '13 at 05:07
  • i have use of mysql aswell, can i keep both, check my update for connection.php – sdf asdfad Jun 26 '13 at 05:10
  • could i test pdo another way? by just adding something to auto table like a year and make and see if it works, it would work on mysql – sdf asdfad Jun 26 '13 at 05:12
  • @sdfasdfad don't understand why you would want to keep it since you are using PDO which is far better and safer. I have updated my answer, see how your PDO should be, also check my function and see how I placed the `global $dbh` you should have that on yours, once you do that try to run the code and let me know what error u get. – Prix Jun 26 '13 at 05:13
  • okay i think i got some errors `Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: no parameters were bound' in C:\xampp\htdocs\cardealerwins\core\functions\users.php:51 Stack trace: #0 C:\xampp\htdocs\cardealerwins\core\functions\users.php(51): PDOStatement->execute(NULL) #1 C:\xampp\htdocs\cardealerwins\adding_a_car.php(188): add_a_car(Array, Array) #2 C:\xampp\htdocs\cardealerwins\admin.php(25): include('C:\xampp\htdocs...') #3 {main} thrown in C:\xampp\htdocs\cardealerwins\core\functions\users.php on line 51` – sdf asdfad Jun 26 '13 at 05:24
  • @sdfasdfad let's make your question easier to read, remove all the unneeded code from your question, and place only the code of the function add_a_car, and your connect.php with the actual code you have for both and the current error you're getting. As for the error, it refers to the parameters on `$sth->execute($final);` being empty. – Prix Jun 26 '13 at 05:27
  • WOW just WOW man you are my savior, i dont know what i would of done with out you man, probably just give up, thanks for helping i added the last array merge line you recomended and it inserted the data :) amazing, please let me repay you, im going to sell this for 3k let me give you something please titanprofesa @ gmail [.]com – sdf asdfad Jun 26 '13 at 05:29
  • @sdfasdfad glad you got your problem solved now make sure you convert the rest of your code to use PDO and throw away the mysql_*, they are not good to your health. – Prix Jun 26 '13 at 05:33
  • got that.! :) please email me, itll take me a few minutes to paypal you or transfer some gas money.. my name is jess very nice meeting you – sdf asdfad Jun 26 '13 at 05:35
  • @sdfasdfad don't worry about money as long you've learned something from all these messages we exchanged here that's all good. Now I'm head to bed so have a nice day. – Prix Jun 26 '13 at 05:36