why i cannot mix prepared statements and PDO query()? [duplicate]

Why the following code prints nothing?:

<?php
error_reporting(E_ALL);
$db = new PDO("sqlite::memory:");
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("CREATE TABLE IF NOT EXISTS book (
  id INTEGER PRIMARY KEY,
  name text,
  amount integer,
  day text
);
");

$stmt = $db->prepare('insert into book(name,amount,day) 
        values(:name,:amount,:day)');
        $stmt->bindValue(':name', 'foo', SQLITE3_TEXT);
        $stmt->bindValue(':amount', 102, SQLITE3_INTEGER);
        $stmt->bindValue(':day', '2022-12-28', SQLITE3_TEXT);
        $stmt->execute();

$result = $db->query("select * from book where `name`='foo'");
foreach($result as $r){
                        print $r['name']."n";
}

When i insert the row with PDO query(), then it would work, why?

Fatal error: During inheritance of ArrayAccess (only in dev environment)

In the stage environment, this is not happening. But in the dev environment which I am currently setting up, I receive following error:

Fatal error: During inheritance of ArrayAccess: Uncaught ErrorException: Return type of SlimEnvironment::offsetExists($offset) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/html/api/lib/slim/Slim/Environment.php:186

Both environments have the same PHP version 8.1.12 (cli). I assume that it might be a configuration issue. But by comparing the phpinfo, I can’t say which setting might be responsible for this inconsistent behavior.

I breaked it down with following tests:

test-plain.php

<?php

class Foo implements ArrayAccess
{
    public function offsetExists(mixed $offset): bool
    {
    }

    public function offsetGet(mixed $offset): mixed
    {
    }

    public function offsetSet(mixed $offset, mixed $value): void
    {
    }

    public function offsetUnset(mixed $offset): void
    {
    }
}

$object = new Foo();
var_dump($object);

Both environments outputs the same. So the implementation of ArrayAccess actually works.

object(Foo)#1 (0) { }

test-slim.php

<?php
require 'lib/slim/Slim/Slim.php';

SlimSlim::registerAutoloader();
$app = new SlimSlim();
$app->run();

Stage environment shows a clean framework specific “404 Page Not Found” error page.
Dev environment breaks with the fatal error above.

Any idea why this behaves differently? Again, both environments have the same PHP version 8.1.12 (cli).

error don’t hold value in increase and decrease quantity in php using loop

I have a problem, when I click to other -/+ in new row, the old row return initial value. How can I fix it?

<?php
$arr = array(1, 2, 3);
for ($i = 0; $i < 3; $i++) {
    $arr[$i] = isset($_POST["item".$i]) ? $_POST['item'.$i] : $arr[$i];
    if (isset($_POST['incqty'.$i])) {
        $arr[$i] += 1;
    }

    if (isset($_POST['decqty'.$i])) {
        $arr[$i] -= 1;
    }
}
?>
<?php

for ($i = 0; $i < 3; $i++) {

?>
    <form method='post' action='<?= $_SERVER['PHP_SELF']; ?>'>
        <td>
            <button name='decqty<?php echo $i; ?>'>-</button>
            <input type='text' size='1' name='item<?php echo $i; ?>' value='<?= $arr[$i]; ?>' />
            <button name='incqty<?php echo $i; ?>'>+</button>
        </td>
    </form>
<?php
 } 
 ?>

change value when end click other row

How can I insert data to the database?

I want to insert data from website but my website still can’t insert to database mysql. whats wrong with my php code?

this is the html file

<form class="sign-in-up-form" action="book.inc.php" method="POST">
                    <p class="section-title">Booking Form</p>
                    <input class="input-field" type="text" id="name" name="UserName" placeholder="Full name" required>
                    
                    <input class="input-field" type="tel" id="contact" name="UserContact" placeholder="Contact Number" required>
                    
                    <input class="input-field" type="email" id="email" name="UserEmail" placeholder="Email" required>
                    
                    <input id="datetime-book" class="input-field book-field" type="datetime-local" id="date" name="aptDateTime" required>
                    
                    <select class="input-field book-field" name="artistName" id="selArtist" required>
                        <option id="select-placeholder" value="">Please choose an artist</option>
                        <option value="Aurelius">Aurelius</option>
                        <option value="Crocks">Crocks</option>
                    </select>

                    <textarea id="textarea-tattoo-idea" name="aptComment" class="input-field" placeholder="Describe your tattoo idea here..."></textarea>

                    <input class="submit-btn" type="submit" name="submit" value="book">
                </form>

this is the php file

<?php
session_start();
// connect to database

$con = mysqli_connect("localhost","root","","yellowstudios");

if (empty($_POST["UserName"])) {
    die("Name is required");
}

if (!filter_var($_POST["UserEmail"], FILTER_VALIDATE_EMAIL)) {
    die("Valid email is required");
}

// to collect data
if(isset($_POST['submit'])) {

    $UserName = $_POST['UserName'];
    $UserContact = $_POST['UserContact'];
    $UserEmail = $_POST['UserEmail'];
    $aptDateTime = $_POST['aptDateTime'];
    $artistName = $_POST['artistName'];
    $aptComment = $_POST['aptComment'];

    // will insert to DB
    $query = "INSERT INTO bookDB (UserName, UserContact, UserEmail, aptDateTime, artistName, aptComment, aptStat) VALUES ('$UserName', '$UserContact', '$UserEmail', $aptDateTime','$artistName', '$aptComment', ?)";
    $query_run = mysqli_query($con, $query);

    if($query_run)
    {
        // will execute if booking is successful, and will go to next page
        $_SESSION['status'] = "Appointment inserted successfully!";
        header("Location: book.output.php");
    }
    else
    {
        // will execute if booking is not successful, and will go to next page
        $_SESSION['status'] = "Appointment not inserted!";
        header("Location: book.output.php");
    }
}

I looked for typos and everything, but it won’t insert data to database. I also double checked everything.

Laravel – create array of objects and arrays in PHP

I am trying to create an array of objects in laravel php. I have achieved this so far.

but it end up creating a singlee object instead of an array…

I get this output

enter image description here

  $usersData = User::where('user_id', 2)->where("stud_class", $exam_details->exam_class_id)->where("XXXX", $exam_details->exam_branch_id)->get(['name', 'id']);
        foreach ($usersData as $user) {
            $studentsArray = array(
                "student" => $user->name,
                "subjects" => []
            );
            foreach ($exam_data as  $subject) {
                $att_exams =  MODEL::where('XXXXX', $subject->subject_id)
                    ->where('XXXX', $user->id)
                    ->first();
                if ($att_exams) {
                    $marks =  MODEL::where('XXXX', $att_exams->attended_exams_id)->get();
                    $right = 0;
                    $wrong = 0;
                    $total_marks = $marks->sum('XXXX');
                    foreach ($marks as $mark) {
                        if ($mark->XXX== 0) {
                            $wrong++;
                        } else {
                            $right++;
                        }
                    }
                    $total_negative_marks = $wrong * $subject->negative_marks;
                    $subjectsArray[] = array(
                        "subject" => $subject->subject_name,
                        "marks_" => $total_marks - $total_negative_marks,
                    );
                } else {
                    $subjectsArray[] = array(
                        "subject" => $subject->subject_name,
                        "marks_" => 0,
                    );
                }
            }
            $studentsArray["subjects"] = array($subjectsArray);
        }
        return $studentsArray;

Origin going as HTTP in laravel websockets

I am using Laravel websockets but Origin is going http instead of https.

Here are my files

Broadcasting.php

'connections' => [
    'pusher' => [
        'driver' => 'pusher',
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'app_id' => env('PUSHER_APP_ID'),
        'options' => [
            'cluster' => env('PUSHER_APP_CLUSTER'),
            'encrypted' => false,
            'host' => 'domainlink',
            'port' => 6001,
            'scheme' => 'https',
            'useTLS' => true,
            'curl_options' => [
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_SSL_VERIFYPEER => 0,
            ]
     ],
 ],

websockets.php

'ssl' => [
    /*
     * Path to local certificate file on filesystem. It must be a PEM encoded file which
     * contains your certificate and private key. It can optionally contain the
     * certificate chain of issuers. The private key also may be contained
     * in a separate file specified by local_pk.
     */
    'local_cert' => 'fullchain.pem',

    /*
     * Path to local private key file on filesystem in case of separate files for
     * certificate (local_cert) and private key.
     */
    'local_pk' =>'privkey.pem',

    /*
     * Passphrase for your local_cert file.
     */
    'passphrase' => env('LARAVEL_WEBSOCKETS_SSL_PASSPHRASE', null),

    'verify_peer' => false,

    'allow_self_signed' => true,
    
],

app.js

  window.Echo = new Echo({
     broadcaster: 'pusher',
     key: "L698gJH67",
     encrypted: false,
     wsHost: window.location.hostname,
     wssHost: window.location.hostname,
     wsPort: 6001,
     wssPort: 6001,
     forceTLS: true,
     disableStats: true,
     enabledTransports: ['ws', 'wss'],
  });

enter image description here

Connection with socket is successful but while broadcasting message I am getting Invalid auth signature provided and if I change schema to http in broadcast.php I get Pusher error: cURL error 52: Empty reply from server.

Not sure what I am doing wrong. Thanks for the help in advance.

Append php commands to another file causes errors

I would like to append a php command to another file to appear exactly as the $string contents shows between the quotes. The idea is shown below:

$string = "<?php include_once $_SERVER['DOCUMENT_ROOT']./content/single_page_loader.php; ?>";
file_put_contents($existing_file, $string.PHP_EOL, FILE_APPEND);//append to end 

The <?php and other php commands seem to produce errors such as:

Parse error: syntax error, unexpected string content "", expecting "-" or identifier or variable or number in C:wamp64wwwdev.xxxxxx.comtest.php on line 40

How can this be achieved?

Thanks!

Combinations in multidimensional array keeping the keys PHP

I have a problem with site transport. I have to combine all arrays preserving the keys and extrapolate all the combinations.
The internal values must not repeat and must combine in order.

The internal values are the bus stops and they are adjacent. example Location 58 to location 61, location 61 to location 140 and so on. this is how metro stops work.

I get on the bus at the stop id_sott=58 and I have to go to the stop id_sott=65.

id_sott 58 to id_sott=65.

the foreign keys (in this case 1, 66, 68) are very important because they are groups of hours that the bus or metro passes.

What routes are available?

I need a route with times

This is my array

$arrayxcorse=array ( 
'1' => array (  '58', '61',  '140',  '142', '91',  '118',  '65' ),
'66' => array (  '140', '62', '91', '65' ),
'68' => array (  '65' ,'140',  '58',  '142' )
);

From start and end, I want these combinations:

$start=58;
$end=65;


combination1= array( '58', '61',  '140',  '142', '91',  '118',  '65' );

combination2= array('1' => array ( '58', '61',  '140'), '66' => array ( '140', '62', '91','65'));

combination3= array('68' => array ( '58','142'), '1' => array ('142', '91', '118','65' ) );

I thought about creating a recursive and merge function but it’s wrong. with this function and with a flat array I don’t have the key

$arrayxcorse=['58-61','61-140','140-142','142-91','91-118','118-65','140-62','62-91 ','91-65','65-140','140-58','58-142'];



$start=$_GET['par'];
$end=$_GET['arr'];

function ctr_doppioni($path,$ultimo){

 $tuttiiprimi=[];
 $tuttisecondi=[];
 $flag=1;
   for($u=0;$u<count($path);$u++){
     $thsval=explode("-",$path[$u]);
     $tuttiiprimi[$thsval[0]][]=$thsval[0];
     $tuttisecondi[$thsval[1]][]=$thsval[1];


     if(count($tuttiiprimi[$thsval[0]])>1 || count($tuttisecondi[$thsval[1]])>1 || ($u<count($path)-1 && ($thsval[0]==$ultimo || $thsval[1] ==$ultimo) )  ){
       $flag=0;
       $u=count($path)-1;//esco
     }
   }
   return $flag;
 }

function getPathTo2(array $array, string $pathEndsWith, string $linkOn = '', $path = [], &$result = []) {


        foreach ($array as $hyphenated) {
            sscanf($hyphenated, '%[^-]-%s', $first, $second);


            if ($first === $linkOn) {

                  if ($pathEndsWith === $second) {
                     $flag=ctr_doppioni($path,$pathEndsWith);
                     if($flag==1){ $result[] = array_merge($path, [$hyphenated]); }
                  }


                    getPathTo2(array_diff($array, [$hyphenated]), $pathEndsWith, $second, array_merge($path, [$hyphenated]), $result);

              }


            }

        return $result;
    }


    $percorsi[]=getPathTo2($arrayxcorse,$end,$start);
    print_r($percorsi);



i saw something similar here but couldn’t adapt
Array permutations in multidimensional array keeping the keys PHP

Thanks for your help

the fopen feature keeps on sending me repeated versions of my form that has been posted when I reload the webpage

here is the html/php

<html>

<form method="post" action="<?php echo $_SERVER["PHP_SELF"] ?>">
Enter message<br> <textarea rows="4" cols="40" name="form"></textarea><br>
<input type="submit">
</form>

<?php
$formvalue = $_POST["form"];
if ($formvalue == TRUE) {
$file = fopen("logindetails", "a");
fwrite($file, PHP_EOL);
fwrite($file, $formvalue);
fclose($file);                     
}
else {
    die();
}
?>

</html>

Now whenever I reload the page the previously submitted value or a new line break appears
How do I solve this

Please help

I expected the form value from the webpage to be submitted and displayed on a file on the server and with each form submit the file to be updated but instead it repeats the previously sent value onto the file with page refresh or if I haven’t filled in anything in the form a blank new line as I added a
attribute to my form

Variation swatches are not showing in wordpress custom theme

I am developing my first wordpress custom theme for the woocommerce and i want to add variation swatches. I have installed variation swatches plugin but it is not showing the swachtches. instead of it it shows somwthing like this:-

enter image description here

I want to know what i am doing wrong? and also the way to customize the variation swatches and php codes to show those variation swacthes of related product anywhere i want.

i can’t get Auth::user(); in laravel

AuthController.php

public function signinAction(Request $request)
{
    $attempt_data = [
        'username' => $request->username,
        'password' => $request->password
    ];

    $login = Auth::attempt($attempt_data);
    if ($login){
        $admin = Auth::user();
        dd($admin);
        $admin->update(['last_login' => now()]);
        return redirect(route('index'))->with('msg','success login');
    }
}

I wanted to get Auth::user(); but $login is true but $admin is null

auth.php


'guards' => [
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'session',
        'provider' => 'users',
    ]
],


'providers' => [
    'admins' => [
        'driver' => 'eloquent',
        'model' => AppModelsAdmin::class,
    ],
    'users' => [
        'driver' => 'eloquent',
        'model' => AppModelsUser::class,
    ],

I change guards
remove admin and change provider change users to admin
i can get Auth::user();
but i want to log in with the
other than ‘web’=>[]


'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'api' => [
        'driver' => 'session',
        'provider' => 'users',
    ]
],

Suming up 35 colums of one record (row) in an attendance sheet database to get total work hours

Hope you all having a good time coding, but I’m stuck with this sql query. Scenario is that i have a simple employee’s database. The data is saved into mysql table. the table has 35 columns. each column corresponds to month date. and i am trying to pick work hours entered in each column for everyone. 35 columns should combine to sum up into total work hours of month for a particular person. and my query isn’t working. it aggregates sum of all columns according to where clause for all the workers and shows it as single result. whereas my requirement is to calculate work hours for each worker separately.
Also please note that i am aware of sql injection and input sanitation shorter column count but here it is not required as this app is for local use only.

i tried sql query with ‘where’ having three criteria for record selection that is: select against specific month, year and work_grade for particular person.

$sql = "SELECT staff_id, `worker_name`, `work_grade`, `m`, `y`,`1`,`2`, sum(`1`+`2`) as `totalhours` FROM tbl_s where `work_grade` ='$_GET[work_grade]' and `m` ='$_GET[month]' and `y` ='$_GET[year]' order by ts_id desc";

The result should be like sum of day 1 of month through last day of month 30 or 31st.
Such as sum of dates: 1+2+3+4+5…..31 = 310 supposing if worker worked for 10 hours daily.
In my sql query here i have shown only 2 columns just to reduce length of sentence for better understanding.

i have already searched numerous seemingly almost similar but could no find either proper details or the answers aren’t comprehensive enough for understanding.

Hoping I will get a solution or an advise.
Thanks!

How to get model instances instead of associative arrays from custom repository’s select query

I have this repository, which works per se:

<?php

namespace HomeinfoSysMon2DomainRepository;

use TYPO3CMSCoreDatabaseConnection;
use TYPO3CMSCoreDatabaseConnectionPool;
use TYPO3CMSExtbaseUtilityDebuggerUtility;
use TYPO3CMSExtbasePersistenceRepository;
use TYPO3CMSExtbasePersistenceQueryResultInterface;

final class CheckResultsRepository
{    
    public function __construct(
        private readonly ConnectionPool $connectionPool
    ) {
    }

    public function findBySystem(int $system) {
        $queryBuilder = $this->connectionPool->getQueryBuilderForTable('checkresults');
        $result = $queryBuilder
            ->select('*')
            ->from('checkresults')
            ->where(
                $queryBuilder->expr()->eq(
                    'system',
                    $queryBuilder->createNamedParameter($system, Connection::PARAM_INT)
                )
            )
            ->executeQuery();
        return $result->fetchAll();
    }
}

However, the data returned by fetchAll() is an array of associative arrays representing the table columns.
I have this model:

<?php

namespace HomeinfoSysMon2DomainModel;

use TYPO3CMSExtbaseDomainObjectAbstractEntity;

class CheckResults extends AbstractEntity
{
    /**
     * @var int $id
     */
    public $id;

    /**
     * @var DateTime $timestamp
     */
    public $timestamp;

    /**
     * @var int $system
     */
    public $system;

    /**
     * @var bool $icmp_request 
     */
    public $icmp_request;

    /**
     * @var string $ssh_login  
     */
    public $ssh_login ;

    /**
     * @var string $http_request 
     */
    public $http_request;

    /**
     * @var string $application_state 
     */
    public $application_state;

    /**
     * @var string $smart_check 
     */
    public $smart_check;

    /**
     * @var string $baytrail_freeze 
     */
    public $baytrail_freeze;

    /**
     * @var string $fsck_repair 
     */
    public $fsck_repair;

    /**
     * @var bool $application_version 
     */
    public $application_version;

    /**
     * @var int $ram_total 
     */
    public $ram_total;

    /**
     * @var int $ram_free 
     */
    public $ram_free;

    /**
     * @var int $ram_available 
     */
    public $ram_available;

    /**
     * @var string $efi_mount_ok 
     */
    public $efi_mount_ok;

    /**
     * @var int $download 
     */
    public $download;

    /**
     * @var int $upload 
     */
    public $upload;

    /**
     * @var string $root_not_ro 
     */
    public $root_not_ro;

    /**
     * @var string $sensors 
     */
    public $sensors;

    /**
     * @var bool $in_sync 
     */
    public $in_sync;

    /**
     * @var int $recent_touch_events 
     */
    public $recent_touch_events;

    /**
     * @var DateTime $offline_since 
     */
    public $offline_since;

    /**
     * @var DateTime $blackscreen_since 
     */
    public $blackscreen_since;
}

What is the correct way to make the above function yield instances of that model instead of associative arrays?

Why do i still get Undefined array key errors if i did everything correctly? [duplicate]

I tried putting “isset()”, i tried putting null, i researched every single solution and NOTHING works.

It says that:
Warning: Undefined array key “GoogleMaps” in C:xampphtdocspaonlineconfig_novapadeiras.php on line 11

For context: My idea is that you are suppost to be able to send a full link from any bakery from Google Maps, but that is what is giving me problems.

This is my code on php :

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['enviar'])) {

  $conn= mysqli_connect('localhost', 'root', '', 'paonline') or die("Falho de connexao:" .mysqli_connect_error());
  
  if(isset($nome) && isset($localidade) && isset($padeiramap));

$nome =       $_POST['nome'];
$localidade = $_POST['localidade'];
$padeiramap = $_POST['GoogleMaps'];

return $GoogleMaps[$padeiramap] ?? null;

$sql= "INSERT INTO 'padeiras' ('nome','localidade','GoogleMaps') VALUES ('$nome','$localidade','$padeiramap')";

$query = mysqli_query($conn,$sql);
if($query) {
    echo "Dados enviados! Agora o nosso equipo revisara se a sua padeira tem todo o preciso para ser colocada em nossa web.";
}
else {
    echo "Aconteceu um erro! Revise se tem introducido bem os dados na sua padeira ou espere um tempo e volte a temtar registrar a sua padeira.";
}

}

?>

and this is my code in the html form:

<fieldset>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method='POST'>
            <div class="form-group">
                <center><label>Nome da padeira</label></center>
                <center><input type="text" name="nome" id="nome" required></center>
            </div>    
            <div class="form-group">
                <center><label>Localidade</label></center>
                <center><input type="radio" name="localidade" value="Murtosa" required>Murtosa</center>
                <center><input type="radio" name="localidade" value="Estarreja" required>Estarreja</center>
                <center><input type="radio" name="localidade" value="Ovar" required>Ovar</center>
            </div>
            <div class="form-group">
                <center><label>Link no Google Maps:</label></center>
                <center><input type="url" name="padeiramap" id="padeiramap" required></center>
            </div>  
            <center><div class="form-group">
                <input type="submit" id="Enviar" name="enviar">
                <input type="reset" id="Reiniciar" name="reiniciar">
            </div></center>
        </form>
 </fieldset>

</body>
</html>

This are two separated files on the same folder by the way.

And please, before you ask:

  • NO, i do not know what do you mean with having “MySQL installed”. If you are talking about hacing Apache and MySQL started in XAMPP them yes, i have them both.
  • YES, i have removed the $bd and $link connections so it not longers causes conflict.
  • NO, I do not know what do you mean with my code been vulnerable to SQL injections, is not suppost to be a public web.
  • Avoid downvoting my question. I am asking for help with something very important for me and i would not like it if i got spitted on my face.