cereal 1,524 Nearly a Senior Poster Featured Poster

Sorry, but it seems the attachment is not showing on your post. Once uploaded, in case of images, you have to choose how to display the attachment. Retry or, if possible, show us an online version of this page.

cereal 1,524 Nearly a Senior Poster Featured Poster

but it is showing red link in the console with no error message or status.

If you meant Google Chrome Console then can you check if there is any additional information in the Network tab? When a request fails even if the status code is not returned it should say something like (failed) and, by hovering, it should return a description of the error, like: (failed) net::ERR_BLOCKED_BY_CLIENT.

From this we should be able to understand if the request is actually sent to the server or if it is blocked by the browser. You can also check to the access & error logs of the web server to find if a request was received.

And: can you successfully send the request through a normal form?

cereal 1,524 Nearly a Senior Poster Featured Poster

Reading through the php manual, it appears that when I use the filter_input method I shouldn't put the first parameter (type) in quotes

My fault, sorry, I wrote it without checking the documentation and got confused with the syntax used in the Guzzle client... o_o'

Bye!

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, I'm not sure I've understood your request and I haven't used L4 in a while, but:

with('message','Message has been sent',compact('account','pageTitle'))

Should not work, as the with() method accepts only two parameters:

You are feeding three. Instead you could try:

with('message', array('Message has been sent', array('account','pageTitle')))

But I'm not sure it will work, and if it works, you can access it through Session::get('message')[0] and Session::get('message')[1]['account'] or something like that.

So why don't you use Session::flash() before the redirect?

Session::flash('account', 'pageTitle');
cereal 1,524 Nearly a Senior Poster Featured Poster

how do I fix that?

Define the allowed request method and sanitize the input, as in my previous example, that should limit improper submissions.

Nope, I didn't get anything.

Ok, I thought it worked because your page returned with success.

You can find more information about forms security here:

cereal 1,524 Nearly a Senior Poster Featured Poster

Keep in mind that your server side script is not safe: an attacker could send a request directly to the formhandler.php script and this will execute without control.

Also the script should check the request method, for example by clicking (i.e. executing a GET request) on:

it should lead to unexpected results, because the $_POST array is not set. I did it and you will probably received a mail with some PHP warnings. It's worth to fix this, because scanners always target form actions in search of errors. You should check each index key of the $_POST array that you want to use. So, you should do something like this:

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $firstName = filter_input('POST', 'firstname', FILTER_SANITIZE_STRING);
    $lastName = filter_input('POST', 'lastname', FILTER_SANITIZE_STRING);
    $emailAddress = filter_input('POST', 'emailAddress', FILTER_SANITIZE_EMAIL);
    $message = filter_input('POST', 'message', FILTER_SANITIZE_STRING);
    $website = filter_input('POST', 'website', FILTER_SANITIZE_URL);

    # all other code here
}

About return values of filter_input():

Value of the requested variable on success, FALSE if the filter fails, or NULL if the variable_name variable is not set. If the flag FILTER_NULL_ON_FAILURE is used, it returns FALSE if the variable is not set and NULL if the filter fails.

Check: http://php.net/filter-input

cereal 1,524 Nearly a Senior Poster Featured Poster

By the way: you can use $deck = range(1, 52); to get the numbers array, each entry will be an integer.

cereal 1,524 Nearly a Senior Poster Featured Poster

The specific error raises because the index key does not exists in the array, example:

$data['a'] = 'hello';

print $data['a']; # will print 'hello'
print $data['b']; # will raise the error

By using array_key_exists('index', $_FILES) you can avoid such problems. But you have to consider that, usually, the $_FILES array is populated after you send an upload request. It seems you're running upload_images() without testing the request method or if the $_FILES array exists.

As simple solution, try:

if($_FILES)
    upload_images();

And in general you should modify the function to work with arbitrary input and paths.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

CodeIgniter 2.* is in legacy mode and reached end-of-life on October 31, 2015. It means they are not going to support it anymore. It's there for projects already developed under this code, but you should not use it to start new ones, as if a security issue is found, you would have to patch it on your own.

Switch to Codeigniter 3.* and follow their user guide:

There is a tutorial which explains the framework basics.

cereal 1,524 Nearly a Senior Poster Featured Poster

What do you mean that my HTML MUST have a <head> tag? ...

It seems I'm still learning the basics. You're right, it's not required, what is required is the title tag, an not even in all cases:

If the document is an iframe srcdoc document or if title information is available from a higher-level protocol: Zero or more elements of metadata content, of which no more than one is a title element and no more than one is a base element.
Otherwise: One or more elements of metadata content, of which exactly one is a title element and no more than one is a base element.

And:

The title element is a required child in most situations, but when a higher-level protocol provides title information, e.g. in the Subject line of an e-mail when HTML is used as an e-mail authoring format, the title element can be omitted.

In practice:

<!DOCTYPE html>
<html>
    <title>Hi</title>
    <body>
        <p>...</p>
    </body>
</html>

is valid. Sorry and thanks for pointing that out.

I wasn't getting an error or anything it's jut that I noticed that my POST variables appeared in the URL, .com?var=x&var=y

Is this still happening?

cereal 1,524 Nearly a Senior Poster Featured Poster

The form works fine for me, it executes a POST request and the parameters are sent as request body, not in the GET segment. I cannot execute the code of the Inmate class, how is this related with the issue?

The only problem with current setup, a part the Inmate code block, is that those print statements at lines 28 and 29 will raise a notice for undefined index, when the page is accessed through a GET request or if those indexes are not set in the POST request.

Also the HTML must have an <head> part.

However, both issues should not cause the problem you are reporting.

cereal 1,524 Nearly a Senior Poster Featured Poster

Maybe your IDE was tricked by the string concatenation, I don't know, what are you using? You should add the PDO error methods to catch the errors.

Anyway, you can write that query in one single string:

$query = $this->db->prepare("INSERT INTO gy_product_detail(product_id, product_detail, product_image_back, product_image_left, product_image_name, product_image_right, product_rate, product_discount) VALUES (last_insert_id(), :product_details, :product_image1, :product_image2, :product_image3, :product_image4, :rate, :discount)");

Or to make it more readable:

$query = $this->db->prepare("
            INSERT
                INTO gy_product_detail(product_id,
                                       product_detail,
                                       product_image_back,
                                       product_image_left,
                                       product_image_name,
                                       product_image_right,
                                       product_rate,
                                       product_discount)
                VALUES (last_insert_id(),
                        :product_details,
                        :product_image1,
                        :product_image2,
                        :product_image3,
                        :product_image4,
                        :rate,
                        :discount)
        ");

Besides this, try to reply with a post and use upvote/downvote comments only when necessary, these will affect users reputation and while it is nice to receive positive rep, it's not nice to receive negative rep, as your previous downvote, if not deserve it... ^__^

cereal 1,524 Nearly a Senior Poster Featured Poster

Can you show your form code?

Anyway you can setup a simple echo script (echo.php) and see what really happens when a request is sent. You need to open two terminal windows.

Start with this script:

<?php

if($_POST)
    echo 'POST:' . PHP_EOL . print_r($_POST, TRUE);

if($_GET)
    echo 'GET:' . PHP_EOL . print_r($_GET, TRUE);

if($_FILES)
    echo 'FILES:' . PHP_EOL . print_r($_FILES, TRUE);

if($_COOKIE)
    echo 'COOKIE:' . PHP_EOL . print_r($_COOKIE, TRUE);

Then start the internal server in the first terminal:

php -S localhost:8000

And send your requests to this address: http://localhost:8000/echo.php.
From the second terminal window use curl or httpie and send some requests, for example:

http -vf :8000/echo.php id==123 cat=fruit color=red

Here we will append a variable to GET id=123 and two variables to POST cat=fruit&color=red, the request will look like this:

POST /echo.php?id=123 HTTP/1.1
Accept-Encoding: gzip, deflate, compress
Content-Length: 19
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Host: localhost:8000

cat=fruit&color=red

This is what you would type into a telnet session. As you can see the GET is appended in the first statement:

POST /echo.php?id=123 HTTP/1.1

Following there are the request headers, while post variables are appended to the request body, which comes one blank line after the request headers.

If you upload a file, for example:

echo "Hello World" > /tmp/test.txt

and send the request:

http -vf :8000/echo.php id==123 cat=fruit color=red file@/tmp/test.txt

You get:

POST /echo.php?id=123 HTTP/1.1
Accept-Encoding: gzip, deflate, compress
Content-Length: 334
Content-Type: multipart/form-data; boundary=8b41bb14137f4b60a4560f05e149051c
Host: localhost:8000
User-Agent: HTTPie/0.8.0

--8b41bb14137f4b60a4560f05e149051c
Content-Disposition: …
cereal 1,524 Nearly a Senior Poster Featured Poster

Ok,

now I see there is an error on line 23 of your first post, you're missing the closing VALUES() parenthesis:

 ":rate,:discount");

It should be:

 ":rate,:discount)");
cereal 1,524 Nearly a Senior Poster Featured Poster

Happy New Year! ^__^

cereal 1,524 Nearly a Senior Poster Featured Poster

@shany

Hi, consider that MySQL will not return the last inserted id if:

  • the table does not have a column with the auto_increment attribute
  • or if you manually feed the id

Example:

-- table without auto_increment column
CREATE TABLE IF NOT EXISTS `test` (
    `tid` INT UNSIGNED NOT NULL PRIMARY KEY,
    `msg` VARCHAR(50) NOT NULL
);

-- insert, no auto_increment
INSERT INTO `test` (`tid`, `msg`) VALUES(1, 'a');
INSERT INTO `test` (`tid`, `msg`) VALUES(2, 'b');
INSERT INTO `test` (`tid`, `msg`) VALUES(3, 'c');

-- get last id, will return 0
SELECT last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                0 |
+------------------+
1 row in set (0.00 sec)

-- show table statement
SHOW CREATE TABLE `test`;
+-------+-----------------------------------
| Table | Create Table                  
+-------+-----------------------------------
| test  | CREATE TABLE `test` (
  `tid` int(10) unsigned NOT NULL,
  `msg` varchar(50) NOT NULL,
  PRIMARY KEY (`tid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------+-----------------------------------

-- show contents
SELECT * FROM `test`;
+-----+-----+
| tid | msg |
+-----+-----+
|   1 | a   |
|   2 | b   |
|   3 | c   |
+-----+-----+
3 rows in set (0.00 sec)

-- alter table to add auto_increment
ALTER TABLE `test` MODIFY `tid` INT UNSIGNED NOT NULL AUTO_INCREMENT;

-- new table statement, with auto_increment
+-------+--------------------------------------------------
| Table | Create Table                                     
+-------+--------------------------------------------------
| test  | CREATE TABLE `test` (
  `tid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `msg` varchar(50) NOT NULL,
  PRIMARY KEY (`tid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1 |
+-------+-------------------------------------------------

-- insert id manually
INSERT INTO `test` (`tid`, `msg`) VALUES(4, 'd');

-- …
shany0786 commented: see my post +1
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, check the Hoa Project:

In particular:

You can embed this code by using composer, which is supported by the latest version of CodeIgniter.

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

Memcached is not available, it is in Ondřej ppa, but still not official:

cereal 1,524 Nearly a Senior Poster Featured Poster

I'm not sure I've understood your request, if you want to know how to append segments to a link and make it work with a specific logic, then you can use routes. For example, you have a controller application/controllers/ListingAds.php that looks like this:

<?php

class ListingAds extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model(['ads']);
    }

    public function index()
    {
        $data['listings'] = $this->ads->getAll();
        $this->load->view('listings/index', $data);
    }

    public function category($cat)
    {
        $data['listings'] = $this->ads->get($cat);
        $this->load->view('listings/category', $data);
    }

    public function subCategory($cat, $name)
    {
        $data['listings'] = $this->ads->getSub($cat, $name);
        $this->load->view('listings/sub', $data);
    }
}

In your application/config/routes.php file you write:

$route['listings/ads/(:any)/(:any)'] = 'listingAds/subCategory/$1/$2';
$route['listings/ads/(:any)'] = 'listingAds/category/$1';
$route['listings/ads'] = 'listingAds/index';

This allows you to append parameters to the original link and to send the request to a specific method of the controller, for example:

# load index()
http://localhost/listings/ads

# load category()
http://localhost/listings/ads/adobe

# load subCategory()
http://localhost/listings/ads/adobe/lightroom

The order of the routing rules is important:

Routes will run in the order they are defined. Higher routes will always take precedence over lower ones.

From: https://codeigniter.com/user_guide/general/routing.html

For the log, here's the model application/models/Ads.php used in the example:

<?php

class Ads extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    public function get($cat)
    {
        return $cat;
    }

    public function getSub($cat, $name)
    {
        return "$cat $name";
    }

    public function getAll()
    {
        return 'All';
    }
}

Which is where you would get the database results for your controller. Hope I've understood your request.

cereal 1,524 Nearly a Senior Poster Featured Poster

Just give arguments to the ads() controller, for example:

public function ads($cat, $add_name) {
    $data['cat'] = $cat;
    $data['add_name'] = $add_name;

    $this->load->view('ads', $data);
}

In this case the url would look like:

  http://localhost/directoryname/listings/ads/categoryname/name

Otherwise use $this->input->get():

  public function ads() {
    $data['cat'] = $this->input->get('cat');
    $data['add_name'] = $this->input->get('add_name');

    $this->load->view('ads', $data);
}

For more info look at:

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,
small addition: look at R language, which is used to find patterns into data structures:

To know how this is applied search for machine learning topics. Some publications about this can be found at Facebook's research website:

Recently an Open AI project started, you can follow them here:

Bye!

cereal 1,524 Nearly a Senior Poster Featured Poster

No, from SQL injection you're safe with prepared statements, but you are exposed to an XSS attack, here:

echo "<div class='alert alert-success' role='alert'>Well done! You successfully created user: <b>".$_POST['username']."</b></div>";

echo "<div class='alert alert-danger' role='alert'>Oh snap! Failed to create new user: <b>$_POST[username]</b></div>";

$_POST is not sanitized, so I could inject javascript or an iframe. The Google Chrome XSS Auditor in this case will raise an alert, which is visible in the developer console.

Use filter_input() if you want to return the contents to the page:

rubberman commented: Good point. I would have missed that. +13
diafol commented: Great explanation of XSS +0
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

best solution would be to get data through mysqldump and then push the backup into the server. By the way, if there were InnoDB tables then you also need ibdata files otherwise moving the files will not work. Also if there were user defined functions and stored procedures you would need mysql.func and mysql.proc contents.

Try to follow the suggestions in this thread, it could help:

diafol commented: good points +15
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, you should give us more details:

  • what looks like the input?
  • are you using utf8 or another encoding?
  • do you get the expected input?
  • do you get the expected output from the preg_replace()?

At the moment your preg_replace() pattern is removing spaces and special characters (like èéàòìùçñđĸ) from the search query.

Possibly you should not use preg_replace() to sanitize the input, filter_input() is a better option as the prepared statements for your queries.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hm, lol, ok, it was so similar I made a mistake :D

So, your Hash::make() method should look like this:

public static function make($string, $salt=''){
    return hash('sha256', $string.$salt);
}

With two only arguments in the hash() function, correct? If for some reason you have a comma in between $string and $salt then you would get binary data in raw format, because the hash() function would read $salt as the third argument.

Example:

print hash('sha256', 'test', 'salt');
# outputs
ЁL}e/ZO,]l

print hash('sha256', 'test' . 'salt');
# outputs
4edf07edc95b2fdcbcaf2378fd12d8ac212c2aa6e326c59c3e629be3039d6432

For reference I'm checking the code through this repository, which seems written by one of those participants:

If the above suggestion still doesn't help, please share the code or a repository with your test code, I will not go through the linked tutorial.

cereal 1,524 Nearly a Senior Poster Featured Poster

If you're using Illuminate Hasher then it should look like:

if(Hash::check($password, $this->data()->password))

rather than your previous IF statement, because the hasher will generate a different result each time, so you cannot compare them directly. This is basically doing:

public function check($value, $hashedValue, array $options = [])
{
    if (strlen($hashedValue) === 0) {
        return false;
    }
    return password_verify($value, $hashedValue);
}

If you're using something different, please point me to the library, so that I can check their documentation.

See:

cereal 1,524 Nearly a Senior Poster Featured Poster

Good for you, did you understood what caused the issue?

cereal 1,524 Nearly a Senior Poster Featured Poster

No error? Sure it's Hash::make() and not Hash::check()?

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi! It happens because:

$data = $this->_db->get('users', array($field, '=', $user));

is not returning the object. It could be because the query failed or for something else, sure _db it's a property and not a method? For example:

$data = $this->_db()->get('users', array($field, '=', $user));

What can be returned by the get() method? If there are cases in which your get() can return something different from the object, then you should check it by using is_object():

if(is_object($data) && $data->count())
cereal 1,524 Nearly a Senior Poster Featured Poster

At this point I would check the contents of the $error variable, if any, and set few die() to check which IF statement is working and which fails. I'm supposing im_id and im_album_id are defined as a multiple-column unique index:

Otherwise the first select query could return more than one row and this IF statement will fail, To start set:

if($result && mysql_num_rows($result) == 1)
{
    die('First select works');

And try the DELETE action, if you reach it, remove it and after the delete query set:

if(mysql_query($sql) && mysql_affected_rows() > 0)
{
    die('Delete query works');

And try again. If you reach it, we know both queries are working fine, at least in a case, and so there could be an issue with the unlink() function, which could be read/write permissions or wrong path.

The value of GALLERY_IMG_DIR is a internal path, not an HTTP link, correct?

cereal 1,524 Nearly a Senior Poster Featured Poster

I think I've understood where is the issue (finally :D): $_GET['album'] is set but it does not return any value. At line 28 of your last code version you had:

$album = isset($_GET['album']) ? $_GET['album'] : '';

Which, will initialize the variable but it will not return nothing when opening the script for the first time because, from what I see, the page will not have a query string with this value. In other words you probably can open the page like this:

http://site.tld/script.php

and/or:

http://site.tld/script.php?album=123

So the value of $album in the first case be empty. Later, in the while loop, you have the javascript function with:

javascript:deleteImage(<?php echo "'$album', '$im_id'"; ?>);

Which should get the value of album from $row rather than the $album variable previously set. The extract() function will initialize $im_id, it will not initialize $album because it DOES NOT exists in the columns returned by $row. So:

  1. you don't get a notice for undefined variable $album;
  2. the $album value arriving here is the one set at line 28 which, as said, can be empty.

I think you can solve the issue by changing the SELECT query at line 61 to return the im_album_id column:

SELECT im_id, im_album_id, im_title, im_thumbnail, DATE_FORMAT(im_date, '%d-%m-%Y') AS im_date FROM tbl_image

And change the javascript code to:

javascript:deleteImage(<?php echo "'$im_album_id', '$im_id'"; ?>);

After these changes the IF conditional statement should work. And var_dump() should return the expected values.

cereal 1,524 Nearly a Senior Poster Featured Poster

Set:

echo "<pre>";
var_dump($_GET);
echo "</pre>";

in top of the script, then press the delete button and paste results here.

cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, then $_GET['delete'] will be set but it will be empty, by consequence the IF statement will fail. Try to change this line:

$delete  = array_key_exists('delete', $_GET) ? trim($_GET['delete']) : NULL;

To:

$delete  = array_key_exists('delete', $_GET);

Now we get a boolean and we don't need anymore to check the variable value. The IF statement changes from:

if( ! empty($delete) && ! empty($albumId) && ! empty($imgId))

To:

if($delete && ! empty($albumId) && ! empty($imgId))

Or more explicitly:

if($delete === TRUE && ! empty($albumId) && ! empty($imgId))

At this point the conditional statement should work fine.

cereal 1,524 Nearly a Senior Poster Featured Poster

Replace code from line 2 to 24 with:

$error = FALSE;

// check if index key exists and trim, else set it to NULL
$delete  = array_key_exists('delete', $_GET) ? trim($_GET['delete']) : NULL;
$albumId = array_key_exists('album', $_GET) ? trim($_GET['album']) : NULL;
$imgId   = array_key_exists('imgId', $_GET) ? trim($_GET['imgIde']) : NULL;

if( ! empty($delete) && ! empty($albumId) && ! empty($imgId))
{
    // get the image file name so we
    // can delete it from the server 
    $sql = sprintf(
            "SELECT im_image, im_thumbnail FROM tbl_image WHERE im_id = '%s' AND im_album_id = '%s'",
            mysql_real_escape_string($imgId),
            mysql_real_escape_string($albumId)
        );

    $result = mysql_query($sql);

    if($result && mysql_num_rows($result) == 1)
    {
        $row = mysql_fetch_assoc($result);

        // and then remove the database entry
        $sql = sprintf(
                "DELETE FROM tbl_image WHERE im_id = '%s' AND im_album_id = '%s'",
                mysql_real_escape_string($imgId),
                mysql_real_escape_string($albumId)
                );

        // remove the image and the thumbnail from the server
        // only if DELETE query is successful
        if(mysql_query($sql) && mysql_affected_rows() > 0)
        {
            unlink(GALLERY_IMG_DIR . $row['im_image']);
            unlink(GALLERY_IMG_DIR . 'thumbnail/' . $row['im_thumbnail']);  
        }

        else
            $error = 'Delete product category failed. ' . mysql_error();
    }

    else
        $error = 'Select product category failed. ' . mysql_error();
}

In practice we initialize some variables ($delete, $albumId & $imgId) by trimming the contents of $_GET, then we refer to these variables for the rest of the script: this is an important point, if you call $_GET['album'] inside the conditional statement you can insert an untrimmed value, clear?

I'm using empty() to check the contents of the variables, please refer to the documentation to check what is …

cereal 1,524 Nearly a Senior Poster Featured Poster

Let's try. The error you are reporting:

MySQL said: Documentation
1064 - 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 '$sql = "SELECT im_image, im_thumbnail FROM tbl_image WHERE im_id = '$imgId' AND ' at line 1

is a bit strange, because MySQL will show the statement starting from the failing point, so you have to look what is set before $sql = "SELECT im_image, ... not after. How this is happening makes me think that, this query, is nested in a previous string or something like that... If you could share your current code, it could help a bit.

Also, running trim() in the IF statement will not affect the original variable, for example:

# value is " hello"
if(trim($_GET['id'])) var_dump($_GET['id']);

You expect string(5) "hello" instead you will get string(6) " hello". Do:

$get['id'] = trim($_GET['id']);

Starting from PHP 5.4 isset() will give different results from what expected in previous versions, see example #2 at http://php.net/isset

In any case isset() will evaluate an empty string to true, so if $_GET['album'] is simply set:

http://link.tld/script.php?album

without adding any value, the function will return it true, for example:

$_GET['album'] = NULL;
var_dump(isset($_GET['album']) ? :FALSE);

$_GET['album'] = '';
var_dump(isset($_GET['album']) ? :FALSE);

will return:

bool(false)
bool(true)

And your query can return unexpected results.

So, can you show your updated code? I'm not sure which version …

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, in which context?

cereal 1,524 Nearly a Senior Poster Featured Poster

Are you using an application password? Read here:

cereal 1,524 Nearly a Senior Poster Featured Poster

Yes, you can by using concat_ws() MySQL function, for example:

UPDATE table1 SET color = concat_ws(',', color, 'green') WHERE id = XX;

But it leads to other problems, for more information read this:

diafol commented: Good info +15
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

you are submitting a single string to the PDO constructor:

$connection = new PDO("mysql:host=$host; dbname=$db_name, $db_user, $password");

instead they should be three: dsn, username, password. Or four if appending options:

$connection = new PDO("mysql:host=$host;dbname=$db_name", $db_user, $password);
cereal 1,524 Nearly a Senior Poster Featured Poster

You could do:

$passwd = crypt($_POST["newpassword"]);

# prepare query
$query = sprintf(
            "UPDATE admin SET hash = '%s' WHERE admin_id = %u",
             mysql_real_escape_string($passwd),
             (int)$_SESSION['admin_id']
         );

# perform query
$result = mysql_query($query);
if($result === FALSE)
    echo "Internal server error occurred.";

Where %s stands for string and so it's quoted, and %u stands for unsigned integer in case the admin_id index, in the session array, is an integer.

cereal 1,524 Nearly a Senior Poster Featured Poster

Warning: mysql_query() expects at most 2 parameters, 3 given in admin\modify-password.php on line 40

It happens because this function does not support prepared statements, and it only accepts two arguments:

mixed mysql_query ( string $query [, resource $link_identifier = NULL ] )

Where the first argument is the query, the second is the connection link to the database, which can be omitted, unless you want to connect to multiple databases.

Docs: http://php.net/mysql-query

mexabet commented: Nice tips +3
cereal 1,524 Nearly a Senior Poster Featured Poster

Is it stored as HTML with an <img> tag? If affirmative then you could use a regular expression to extract the image link. For example:

$content = '
    <p>Title</p>
    <div><img class="hello" src="/images/ocean001.jpg" id="img"></div>
    <p>Blue</p>
';

$pattern = '/<img[^>]*src[\s]?=[\s]?["\']?([^"\']*)[^>]*>/i';

preg_match($pattern, $content, $matches);
print_r($matches);

It should return:

 Array
(
    [0] => <img class="hello" src="/images/ocean001.jpg" id="img">
    [1] => /images/ocean001.jpg
)

So in your loop:

$pattern = '/<img[^>]*src[\s]?=[\s]?["\']?([^"\']*)[^>]*>/i';

while ($row = mysql_fetch_array($res))
{
    preg_match($pattern, $row['post_content'], $matches);
    echo'Post Content:' . $matches[1];
}

And replace 1 with 0 if you want the tag. It will be slow. An alternative is to use a DOM library, but in this case you should parse a full document, not a part. If you can, try to separate description from image link before inserting them into the database, and set them together when needed.

Safina_1 commented: thanks, you have done this +0
cereal 1,524 Nearly a Senior Poster Featured Poster

This should give you some information: http://stackshare.io/etsy/etsy

cereal 1,524 Nearly a Senior Poster Featured Poster

A downvote will not lead help, at least from me. I asked you to share what have you done or do I have to write your code without knowing what you really need?

Try to share your form, your receiving script, your query to the database table and maybe then we will be able to suggest you what to do.

cereal 1,524 Nearly a Senior Poster Featured Poster

What have you done?

AazibKhan commented: can help me out with code snippet +0
cereal 1,524 Nearly a Senior Poster Featured Poster

they can be notoriously slow

so true, hope it's going to change with PHP7: https://nikic.github.io/2014/12/22/PHPs-new-hashtable-implementation.html

cereal 1,524 Nearly a Senior Poster Featured Poster

An alternative:

$t = call_user_func_array('array_merge_recursive', $r);

where $r is diafol's example array and it will return:

Array
(
    [sub_total] => Array
        (
            [0] => 1000
            [1] => 120
        )

    [total_tax] => Array
        (
            [0] => 82.5
            [1] => 9.9
        )

    [total] => Array
        (
            [0] => 1087.5
            [1] => 129.9
        )

)

Then do:

$totals = array_map("array_sum", $t);

Will return:

Array
(
    [sub_total] => 1120
    [total_tax] => 92.4
    [total] => 1217.4
)
diafol commented: Aha - the old array functions ploy, eh? heh heh +15
cereal 1,524 Nearly a Senior Poster Featured Poster

As I see it, this is replacing only the last shortcode. If the goal is to replace all the [shortcode ...] blocks with Shortcode displayed, then preg_replace() should work fine:

$matches = preg_replace("/\[(.*?)\]/", "Shortcode displayed", $content);
echo $matches;
cereal 1,524 Nearly a Senior Poster Featured Poster

On line 3 you're looping index 1 of the $matches array:

foreach($matches[1] as $match)

So, due to the structure of this array, $match will be a string. Try this to get the values:

$values = array();

foreach($matches[1] as $match)
    $values[] = str_replace("'", "", explode('shortcode id=', $match)[1]);

But you can change the pattern and get those values through the regular expression:

preg_match_all("/\[shortcode id='(.*?)'\]/", $content, $matches);

The content of $matches should look like:

Array
(
    [0] => Array
        (
            [0] => [shortcode id='generate']
            [1] => [shortcode id='maximum']
        )

    [1] => Array
        (
            [0] => generate
            [1] => maximum
        )

)