cereal 1,524 Nearly a Senior Poster Featured Poster

Also, each subquery requires an alias, for example:

select a.total from (select count(*) as total from tablename) as a;

Otherwise you get an error, to see it use mysql_error(). In addition try this query:

$query=mysql_query("select a.total + b.total as total from (select count(*) as total from message_believe as mb where mb.uid_fk = {$uid}) as a, (select count(*) as total from review_believes as rb where rb.uid_fk = {$uid}) as b") or die(mysql_error());

Bye!

cereal 1,524 Nearly a Senior Poster Featured Poster

If you use the method insertGetId(), Laravel will return correctly, basing on the value of the auto_increment column. Docs:

By using Eloquent, instead, change the column name, for example:

$p               = new Personnel;
$p->first_name   = '...';
$p->middle_name  = '...';
$p->last_name    = '...';
$p->save();
$p->personnel_id; // <- last inserted id

It should work fine.

here is my schema do i need to array all of this ?

Sorry, I do not understand. :)

cereal 1,524 Nearly a Senior Poster Featured Poster

Are you using Eloquent? If yes, right after you save something call the id property, for example:

$post        = new Post;
$post->title = 'Title';
$post->body  = 'Bla bla bla...';
$post->save();

$post->id; // <- last inserted id

Otherwise use the insertGetId() method:

$id = DB::table('users')->insertGetId(
    array('email' => 'john@example.com', 'votes' => 0)
);

As suggested here: http://laravel.com/docs/queries#inserts

cereal 1,524 Nearly a Senior Poster Featured Poster

what should I do?

Use the correct credentials (user and password) to access the database, so change these values in your config file:

$username = "demo"; 
$password = "demo"; 
$host = "localhost"; 
$dbname = "try";

Check always the last line of the error log, since the information is appended to the bottom of the file. To increase the readability of the error log, I suggest you to change line 17 of your config file with this:

$error_message = date('Y-m-d G:i:s') . " [ERROR]: " . $e->getMessage() . "\n\r";
file_put_contents('PDOErrors.txt', $error_message, FILE_APPEND);

It should output a bit better, separating each error by a carriage return.

cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, then how this should work?

Route::get('/getfile/{id}', function($id)
{
    $file = DB::select('SELECT * FROM docs  WHERE gov_docs_id = ?', array($id = Input::get('id')) 
    $data = $file[0]->file;
    return Response::make( $data, 200, array('Content-type' => $file[0]->mime, 'Content-length' => $file[0]->size));
});

In your table the columns mime and size used as parameters in the response are missing, so the current code will return an error.

Pay attention to the last line of the above script:

return Response::make( $data, 200, array(
    'Content-type' => $file[0]->mime,
    'Content-length' => $file[0]->size)
    );

Where the first argument is the blob data, the second argument is the HTTP status (in this case 200) and the third argument is an array with the headers to send with the response: in this case

Content-type is important and it is used to define the type of data you're sending back to the browser, if it is a PDF the mime will be application/pdf, if docx the mime is:

application/vnd.openxmlformats-officedocument.wordprocessingml.document

And so on for each file-type you want to allow in your database.

Content-length is used to send the size of the file.

You should define this information.

As I previously suggested, check my first example, since there I'm already saving this information, otherwise you have to compute them each time you try to download a file.

Also, saving a file directly into a database is not always a good idea, it would be better to save only the filename. But it's your choice.

cereal 1,524 Nearly a Senior Poster Featured Poster

Can you show your table structure? In a MySQL client run:

show create table docs;

And post the results here. The problem can depend on the data saved in the database table: truncated because of the column type, or it can depend on the system used to define the mime type you are assigning to the downloaded file.

If you can post also few rows from the database, just to see how you're saving the data, could be helpful.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, at line 10 use mysqli_error():

if ( ! $result = mysqli_query($con, $query)) {
    printf("Errormessage: %s\n", mysqli_error($con));
}

It should explain the reason that makes the query return boolean FALSE.

Docs: http://php.net/manual/en/mysqli.error.php

cereal 1,524 Nearly a Senior Poster Featured Poster

Yes, in the viewlist, replace the previous loop with a table, for example:

<?php if($id) { ?>
<table>
    <thead>
        <tr>
            <th>Filename</th>
            <th>Data</th>
        </tr>
    </thead>
    <tbody>
        <?php
        foreach($id as $sid)
        {
            echo "
            <tr>
                <td>
                    $sid->name
                </td>
                <td>
                    <button type=\"button\" onclick=\"javascript:location.href='/getfile/$sid->id'\">download</button>
                </td>
            </tr>
            ";
        }
        ?>
    </tbody>
    <tfoot>
        <tr>
            <td></td>
        </tr>
    </tfoot>
</table>
<?php } // end if ?>
cereal 1,524 Nearly a Senior Poster Featured Poster

So, I see:

  1. a view to display the buttons in which you want to load the links to get the files
  2. a controller to save the file
  3. and another to download it.

What is missing is the method from which you will list all the files, for example:

Route::get('/listfiles')
{
    $data['id'] = DB::select("SELECT * FROM tablename");
    return View::make('viewlist', $data);
}

The view viewlist.php:

<html>
    <head>
        <title>List of files</lists>
    </head>
    <body>
        <?php
            foreach($id as $sid)
            {
                echo "
                <input type=\"submit\" onclick=\"javascript:location.href='/getfile/{$sid}'\" />
                ";
            }
        ?>
    </body>
</html>
cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, it will be easier to help you if we can see the controller from which you load the ids of all the files uploaded, for example you're probably using something like:

$data['id'] = DB::select("SELECT * FROM tablename");
return View::make('viewlist', $data);

The DB::select() will return an array, so the above code will translate to:

onclick="javascript:location.href='/getfile/Array'"

To get all the ids you have to use a foreach loop:

@foreach($id as $sid)
    <input type="submit" onclick="javascript:location.href='/getfile/{{{$sid}}}'" />
@endforeach

If you're not using Blade (the templating engine), then the correct code is:

<?php

    foreach($id as $sid)
    {
        echo "
        <input type=\"submit\" onclick=\"javascript:location.href='/getfile/{$sid}'\" />
        ";
    }

?>
cereal 1,524 Nearly a Senior Poster Featured Poster

Good! Are you using Blade? If yes then the id must be $id and surrounded at least from two consecutive curly brackets, three if you want also to sanitize the variable, for example:

/getfile/{{{$id}}} # with Blade

Regarding the onclick attribute, it should work if you try:

onclick="javascript:location.href='/getfile/{{{$id}}}'"
cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, then check the contents of the file PDOErrors.txt, you should be able to read the reason why the connection to the database is failing.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, check line 12 in your config file: the host and dbname values are hardcoded, change the line with:

$db = new PDO("mysql:host={$host};dbname={$dbname}", $username, $password);
cereal 1,524 Nearly a Senior Poster Featured Poster

by the way i tried to look at my database and i saw that the files i've been stored was convert to .TMP ?

Or you're trying to get the extension from getRealPath()? For the extension use:

$ext = Input::file('upload')->getClientOriginalExtension();
cereal 1,524 Nearly a Senior Poster Featured Poster

No, you're still saving the path and the file name which is the temporary name given by the $_FILES array. In your previous code, you wrote only:

$data = fread(Input::file('file')->getRealPath());

Which is wrong if you do not use also fopen() & co. I supposed you were posting dimostrative code, so read the documentation for fread() or use file_get_contents() as in my example.

i already put this on my route do i need to map this on my onclick button ?

Show your code, please.

Docs:

cereal 1,524 Nearly a Senior Poster Featured Poster

Try this in your router.php file:

Route::get('/getfile/{id}', function($id)
{
    $file = Attachment::find($id);
    $data = $file->doc_attachment;
    return Response::make($data, 200, array('Content-type' => $file->mime, 'Content-length' => $file->size));

});

Again, if you're not using Eloquent, then use DB::select() which returns an array, so it would look like this:

Route::get('/getfile/{id}', function($id)
{
    $file = DB::select('SELECT * FROM tablename WHERE id = ?', array($id));
    $data = $file[0]->file;
    return Response::make($data, 200, array('Content-type' => $file[0]->mime, 'Content-length' => $file[0]->size));

});

I suggest you to save the mime-type and the file size while uploading the file, look at my first example, otherwise you have to declare it in someway.

cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, I'm assuming your form is using the enctype attribute, correct?

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

Otherwise the file will not be uploaded. Also the name attribute in your input field is upload not file (as in my example), so your code becomes:

Input::file('upload')->getRealPath())

To be sure, you should always validate the form request, or at least use:

if(Input::hasFile('upload'))
{
    // save data
}

else
{
    // reject
}
cereal 1,524 Nearly a Senior Poster Featured Poster

Can you show the form and your updated code? Also which version of Laravel are you using?

cereal 1,524 Nearly a Senior Poster Featured Poster

Use Input::file('file') instead of Input::get('file'), the file() method gives you access to the $_FILES array.

After doing this you need to read the contents from the path of the temporary file created by PHP while uploading the file, which is given by the method getRealPath(). To read the binary data, you can use PHP functions like file_get_contents() or fread(), for example:

file_get_contents(Input::file('file')->getRealPath());

In your case, this should work:

$data = file_get_contents(Input::file('file')->getRealPath());
DB::table('tablename')->insert(array(
    'doc_attachment'=> $data
    )
);

But doc_attachment needs to be a blob column type, blob it self can store up to 65KB; if the files are big, then use mediumblob capable of 16MB of storage.

cereal 1,524 Nearly a Senior Poster Featured Poster

Do you want to save the files or only the names? In the former case then use something like this:

<form method="post" enctype="multipart/form-data" action="/upload_file">
    <input type="file" name="file" />
    <input type="submit" name="submit" value="upload" />
</form>

And these methods in the router.php file:

Route::get('/upload_form', function()
{
    $data['files'] = Attachment::get();
    return View::make('uploads.form', $data);

});

Route::post('/upload_file', function()
{

    $rules = array(

        'file' => 'required|mimes:doc,docx,pdf',

        );

    $validator = Validator::make(Input::all(), $rules);

    if($validator->fails())
    {
        return Redirect::to('/upload_form')->withErrors($validator);
    }

    else
    {
        if(Input::hasFile('file'))
        {
            $f = Input::file('file');
            $att = new Attachment;
            $att->name = $f->getClientOriginalName();
            $att->file = base64_encode(file_get_contents($f->getRealPath()));
            $att->mime = $f->getMimeType();
            $att->size = $f->getSize();
            $att->save();

            return Redirect::to('/upload_form');
        }
    }

});

I'm assuming the usage of a model Attachment and a table schema like this:

CREATE TABLE `attachments` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `file` longblob NOT NULL,
  `mime` varchar(255) DEFAULT NULL,
  `size` int(10) unsigned NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

If you still have problems show us your code. Bye.

Sikander Nasar commented: This is not a good approach to write logic in route file +0
cereal 1,524 Nearly a Senior Poster Featured Poster

In particular search for autocomplete scripts, for example this:

bye!

cereal 1,524 Nearly a Senior Poster Featured Poster

That happens if the GET request exceeds the LimitRequestLine directive (if you're using Apache), this limit cannot be higher than 8190 bytes, to change it you should modify the source and re-compile Apache:

Reconsider diafol suggestion. Otherwise use the id of the image instead of the encoded string and then retrieve it from the database.

cereal 1,524 Nearly a Senior Poster Featured Poster

Create a script, for example display.php:

$f = $_GET['image'];
header("Content-type: image/jpeg");
echo base64_decode($f);

Now your link becomes:

<a href="display.php?image=<?php echo $img_str; ?>">

    <img src="data:image/jpeg;base64,<?php echo $img_str; ?>" width=150 height=150 />

</a>
cereal 1,524 Nearly a Senior Poster Featured Poster

You could use foreign keys constraints:

If you have doubts, show us the tables schema.

cereal 1,524 Nearly a Senior Poster Featured Poster

I thought EllisLabs announced that they were looking for a new maintainer for CodeIgniter?

Correct.

Version 3.0 is in the repo since 2011 or so, the development slowed down after the decision of EllisLab and currently it is maintained by volunteers. Here is the change of the license to OSL 3.0:

And here's the current status:

cereal 1,524 Nearly a Senior Poster Featured Poster

The stable version is 2.2.0, which is a security upgrade. Version 3.0 is not stable:

I will try it, however I would wait a stable release before using it in production, bye! :)

cereal 1,524 Nearly a Senior Poster Featured Poster

What if two or more images are the largest? Anyway, here's an example with glob():

<?php

$f = glob('./path/*.{jpg,png,gif}', GLOB_BRACE);
$r = array();

foreach($f as $file)
{
    list($w, $h) = getimagesize($file);
    $r[$w*$h][] = array(
            'name'  => $file,
            'width' => $w,
            'height' => $h
        );
}

$keys = array_keys($r);

# all results
echo "<pre>";
print_r($r);
echo "</pre>";

# one of the largest
echo $r[max($keys)][0]['name'];

# array with the widest images
echo "<pre>";
print_r($r[max($keys)]);
echo "</pre>";

Bye!

cereal 1,524 Nearly a Senior Poster Featured Poster

From your panel you should be able to set up a redirect, check this:

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

It seems you're using some user defined functions: apologize(), query(), render() and redirect() are not PHP functions, so we cannot help much. Check the included file at the top of the script, it should contain those functions and the instructions on their results.

Anyway, on line 51 you wrote:

crypt($_POST["newpassword"], $row["hash"] = $row["hash"]);

if you're referring to the crypt() function in PHP then you need to save the result to a variable and then use an update query, also crypt takes two arguments: string and salt (which is optional), here should be:

crypt($_POST["newpassword"]);

Or for a compare:

crypt($_POST["newpassword"]) == $row["hash"];

But it seems your code just redirects after this action, it should be something like:

$newpwd = crypt($_POST["newpassword"]);
query("UPDATE ...", $newpwd);

But this seems already done in one of the elseif conditions:

else if (query("UPDATE users SET hash = (?) WHERE username = (?)", crypt($_POST["newpassword"]), $_POST["username"]) === false)

On line 31 you wrote:

if(crypt($_POST["curpassword"], $row["hash"]) != $row["hash"]))

You're using the hash as second argument of crypt, i.e. as salt, but this will always compare different unless $_POST["curpassword"] is blank. Correct version should be:

if(crypt($_POST["curpassword"]) != $row["hash"])

Docs:

Hope it helps!

@arunmagar

Hi, mexabet is correct, since PHP 5.4 you can use the short array syntax, as Python lists:

$a = ['a', 'b', 'c'];

Ref: http://www.php.net//manual/en/migration54.new-features.php

mexabet commented: Great insight! +3
cereal 1,524 Nearly a Senior Poster Featured Poster

Have you tried upper()? Example:

select UPPER(CONCAT('CMRC', LPAD(UUID(), 10, '0')));
cereal 1,524 Nearly a Senior Poster Featured Poster

It means $grupa_select (which was $grupa_select2 in your original script) is not defined.

cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, mysql_query() accepts two parameters, the first is mandatory, the second is optional. This:

$pregled = mysql_query("select * from koncerti where grupa_id = ".$grupa_id['id']."");
if (!mysql_query($pregled,$grupa_id,$selektovanje))
{
    die('Error: ' . mysql_error());
}

Should be:

$pregled = mysql_query("select * from koncerti where grupa_id = ".$grupa_id['id']) or die(mysql_error());

Note that at the end of the query I removed the double quotes, that's the reason of the second error:

Error: 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 " at line 1

If you need quotes because the value to compare is a string then write:

$pregled = mysql_query("select * from koncerti where grupa_id = '" . $grupa_id['id'] . "'");

Spot the difference:

grupa_id = '" . $grupa_id['id'] . "'"

Instead of:

grupa_id = " . $grupa_id['id'] . ""
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, define the error you get on line 42 and add mysql_error() to this query and to the previous.

cereal 1,524 Nearly a Senior Poster Featured Poster

Regarding PHP try this:

<?php

$url = $_SERVER['QUERY_STRING'];

if($_GET)
{
    if(filter_var($url, FILTER_VALIDATE_URL) !== FALSE)
    {
        header('Location: ' . $url);
    }
}

Save it, for example, as noref.php, then use a link like this:

http://yourwebiste.tld/noref.php?http://otherwerbsite.tld

I'm not sure it's enough, but I've made few tests and seems to work.

cereal 1,524 Nearly a Senior Poster Featured Poster

@ashalatha

hi, you should open new threads for each new question not directly related to the original.

cereal 1,524 Nearly a Senior Poster Featured Poster

It seems possible, check their documentation:

If you still have problems then paste your code here. Bye!

cereal 1,524 Nearly a Senior Poster Featured Poster

Try to add json_last_error() right after json_decode():

switch (json_last_error()) {
    case JSON_ERROR_NONE:
        echo ' - No errors';
    break;
    case JSON_ERROR_DEPTH:
        echo ' - Maximum stack depth exceeded';
    break;
    case JSON_ERROR_STATE_MISMATCH:
        echo ' - Underflow or the modes mismatch';
    break;
    case JSON_ERROR_CTRL_CHAR:
        echo ' - Unexpected control character found';
    break;
    case JSON_ERROR_SYNTAX:
        echo ' - Syntax error, malformed JSON';
    break;
    case JSON_ERROR_UTF8:
        echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
    break;
    default:
        echo ' - Unknown error';
    break;
}

Source: http://www.php.net//manual/en/function.json-last-error.php

cereal 1,524 Nearly a Senior Poster Featured Poster

It could be line 3 instead of the json_decode function, print_r requires brackets, so change it to:

print_r($data);
cereal 1,524 Nearly a Senior Poster Featured Poster

Try to use the row() method:

$row = $cnt->row();
$new_cnt = $row->Counter_field + 1;

But you could also run a single query:

$this->db->query("UPDATE Job_Description SET Counter_field = Counter_field + 1 WHERE id = ?", array($id));

Docs:

ravi142 commented: @Cereal : Thank You. +1
cereal 1,524 Nearly a Senior Poster Featured Poster

@jKidz

can you explain more please?

ok, if you open a conditional statement, before going to the next condition, you need to declare where you want to stop the execution of the code, you can do this by using a semicolon:

$num = rand(0,1);

if($num == 0)
    echo "empty";
else
    echo "not empty";

But in this case you cannot use more than a line of code for each condition. Then you can use colon:

if($num == 0):
    echo "empty";
else:
    echo "not empty";
endif;

But it's not much used. When you use parentheses it looks like:

if($num == 0)
{
    echo "empty";
}

else
{
    echo "not empty";
}

Now if you add a loop:

if($num == 0)
{
    echo "empty";

    while(true)
    {
        echo " loop";
        break;
    }

} // <-- this was missing in your code

else
{
    echo "not empty";
}

Pritaeas suggested you to align the curly brackets, because indenting correctly your code, helps to read and find problems easily.

Read:

@Sikander

you have to use the folder name.this is only work in css.

Hi, not correct, you can use relative paths in PHP and also with the include() function:

Bye!

jKidz commented: amazing bro +0
cereal 1,524 Nearly a Senior Poster Featured Poster

At line 17 you're closing the paranthesis of the while loop, so add another one:

    } // close while loop

} // close if

else {
jKidz commented: great +1
cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, in your database table create a unique key:

alter table category add unique key(cat_id);

So you cannot insert duplicates and to avoid errors add the IGNORE statement to your insert query, your model now becomes:

function insert_csv($data)
{
    $sql = "INSERT IGNORE INTO category SET cat_id = ?, name = ?"; 
    $this->db->query($sql, array_values($data));

}

And everything should work fine.

Docs: http://dev.mysql.com/doc/refman/5.5/en/constraint-primary-key.html

cereal 1,524 Nearly a Senior Poster Featured Poster

The code which i mentioned above is wrong or right.

It seems correct, but if you have doubts check the error log of CI and paste the errors here.

y did u use set cat_id=? what is ?

It's a query bind in a prepared statement, and it used to escape values: the values are passed to the query through an array of values (so without index keys). In your previous code, at line 23, would translate to something like this:

$insert_data = array(
                   'cat_id'=>$row['Category Id'], 
                    'name'=>$row['Category Name'],
                );

$insert_data = array_values($insert_data);

Or simply:

$insert_data = array(
    $row['Category Id'],
    $row['Category Name']
);

For more information read the last paragraph in this page:

If you have doubts, show us your Model code.

cereal 1,524 Nearly a Senior Poster Featured Poster

If the main plays as master then it's ok, just open 3306 at let the slaves connect to it, you do not need to open ports on slaves because they act as clients. Otherwise you could setup a SSH tunnel:

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, there are few errors here:

$query = "SELECT arCompanyname, arAddress FROM ar WHERE $dropdown like'$search'" or die (mysql_error());

$result = mysql_query($query) or die (mysql_error());
$num=mysql_numrows($result);

$query is a string, so do not include or die(mysql_error()) otherwise the mysql_query() will return FALSE. Then, mysql_numrows() does not exists, the correct function is mysql_num_rows(). If you still get errors then paste them here.

Last, but not least: since you're still learning, I strongy suggest you to avoid the MySQL API: it is deprecated and will be removed from PHP; learn MySQLi or PDO, for more information read this link:

cereal 1,524 Nearly a Senior Poster Featured Poster

Can you connect them directly? If yes, you can use replication:

cereal 1,524 Nearly a Senior Poster Featured Poster

Create a unique key in your table scheme and then use a raw query:

$row = array(
    $row['Category Id'],
    $row['Category Name']
    );

$sql = "INSERT IGNORE INTO tablename SET cat_id = ?, name = ?"; 
$this->db->query($sql, $row);

By using INSERT IGNORE when a duplicate key is found, it will continue without returning an error.

Docs:

cereal 1,524 Nearly a Senior Poster Featured Poster

Maybe some of those browsers are in quirk mode (a.k.a standard mode). These links are for IE9/10, but it should be similar for IE11 too:

cereal 1,524 Nearly a Senior Poster Featured Poster

It seems you want to search and replace a string in a json encoded array, correct? If yes, then each element is probably surrounded by quotes, example:

$a['blog'] = 'blogtitle';
echo json_encode($a);

// outputs {"blog":"blogtitle"}

Which is different from {blog:blogtitle}, the correct code should be:

if($blogname != "")
{
    $r = str_replace('{"blog":"blogtitle"}', '', $content);
}
else
{
    $r = str_replace('{"blog":"blogtitle"}', $blogname, $content);
}

echo $r;
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, you can use substr():

<?php

$reportID = 'MPS141';

echo substr($reportID, 5);

Will return all the characters after MPS14, but you can also create a function to return an array of all the elements of the reportID, an example:

function reportToArray($id)
{
    $data['CompanyName']    = substr($id, 0, 2);
    $data['Article']        = substr($id, 2, 1);
    $data['Year']           = substr($id, 3, 2);
    $data['ID']             = substr($id, 5);
    return $data;
}

print_r(reportToArray($reportID));

Returns:

Array
(
    [CompanyName] => MP
    [Article] => S
    [Year] => 14
    [ID] => 1
)

Docs: http://www.php.net/manual/en/function.substr.php

jKidz commented: thanks buddy +0