My code.
try
{
$sql = "SELECT posts FROM posts WHERE entityid = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$data["entityId"]]);
$result = $stmt->fetchAll();
$sqlq = "UPDATE posts set posts= JSON_SET(posts,'$.heartReactions', ?) WHERE posts(posts,'$.postId',$postId)";
$stmt = $pdo->prepare($sqlq);
$posts = json_decode($result[0][0]);
$postId = $data["postId"];
for ($i = 0; $i < count($posts); $i += 1)
{
$post = $posts[$i];
if ($post->postId == $data["postId"])
{
if ($data["heartState"] == 1)
{
$post->heartReactions += 1;
}
else if ($data["heartState"] == -1)
{
$post->heartReactions -= 1;
}
$postData = $post->heartReactions;
var_dump($stmt->execute([$postData]));
echo $postData;
// echo $post->heartReactions . " - ";
if ($data["laughState"] == 1)
{
$post->laughReactions += 1;
}
else if ($data["laughState"] == -1)
{
$post->laughReactions -= 1;
}
// echo $post->laughReactions;
break;
}
}
}
catch (PDOException $ex)
{
echo $ex;
}
I want to change the key value "heartReactions" from 0 to 1. But it didn't change at all. Also I got an error.
Warning: Undefined variable $postId in D:\xammp\htdocs\AlumniSystemMainFinal\server\functions\pages\profile.php on line 112
PDOException: SQLSTATE[42000]: Syntax error or access violation: 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 ')' at line 1 in D:\xammp\htdocs\AlumniSystemMainFinal\server\functions\pages\profile.php:133
Stack trace:
#0 D:\xammp\htdocs\AlumniSystemMainFinal\server\functions\pages\profile.php(133): PDOStatement->execute(Array)
#1 {main}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
<?php
class dblib {
private $__conn;
function connect(){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webtintuc";
if (!$this->__conn){
try {
$this->__conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$this->__conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
die();
}
}
}
function dis_connect(){
if ($this->__conn){
$this->__conn = null;
}
}
function insert($table, $data)
{
$this->connect();
$field_list = '';
$value_list = '';
foreach ($data as $key => $value){
$field_list .= ",$key";
$value_list .= ",'".$value."'";
}
$sql = 'INSERT INTO '.$table. '('.trim($field_list, ',').') VALUES ('.trim($value_list, ',').')';
$stmt = $this->__conn->prepare($sql);
return $stmt->execute();
}
function update($table, $data, $where){
$this->connect();
$sql = '';
foreach ($data as $key => $value){
$sql .= "$key = '".$value."',";
}
$sql = 'UPDATE '.$table. ' SET '.trim($sql, ',').' WHERE '.$where;
$stmt = $this->__conn->prepare($sql);
return $stmt->execute();
}
function remove($table, $where){
$this->connect();
$sql = "DELETE FROM $table WHERE $where";
$stmt = $this->__conn->prepare($sql);
return $stmt->execute();
}
function get_list($sql){
$this->connect();
$stmt = $this->__conn->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
return $stmt->fetchALL();
}
function get_row($sql){
$this->connect();
$stmt = $this->__conn->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
return $stmt->fetch();
}
function get_row_number($sql){
$this->connect();
$stmt = $this->__conn->prepare($sql);
$stmt->execute();
return $stmt->fetchColumn();
}
}
?>
###post.php
<?php
$link = '';
$where = '';
if (isset($_GET["cat"])) {
$cat = intval($_GET["cat"]);
if ($cat != 0)
$where = "WHERE category_id = $cat";
$link = "cat=$cat&";
}
$sql = "SELECT count(*) FROM posts $where";
$total_records = $homelib->get_row_number($sql);
$limit = 3;
$current_page = isset($_GET['page']) ? $_GET['page'] : 1;
$total_page = ceil($total_records / $limit);
if ($current_page > $total_page){
$current_page = $total_page;
}
else if ($current_page < 1) {
$current_page = 1;
}
$start = ($current_page - 1) * $limit;
$sql = "SELECT * FROM posts $where ORDER BY createdate DESC LIMIT $start, $limit";
$data = $homelib->get_list($sql);
?>
<!-- Blog Entries Column -->
<div class="col-md-8">
<h1 class="my-4">Siêu HOT
<small>tin mới nhất</small>
</h1>
<?php
for ($i = 0; $i < count($data); $i++) {
?>
<div class="card mb-4">
<img class="card-img-top" src="images/<?php echo $data[$i]['image'];?>" height="300px" alt="Card image cap">
<div class="card-body">
<h2 class="card-title"><?php echo $data[$i]['title'];?></h2>
<p class="card-text"><?php echo substr($data[$i]['content'], 0, 200).'...';?></p>
Xem thêm →
</div>
</div>
<?php
}
?>
<!-- Pagination -->
<ul class="pagination justify-content-center mb-4">
<?php
if ($current_page > 1 && $total_page > 1){
echo '<li class="page-item"><a class="page-link" href="index.php?'.$link.'page='.($current_page-1).'">Prev</a></li>';
}
for ($i = 1; $i <= $total_page; $i++) {
if ($current_page == $i)
echo '<li class="page-item disabled"><a class="page-link" href="#">'.$i.'</a></li>';
else
echo '<li class="page-item"><a class="page-link" href="index.php?'.$link.'page='.$i.'">'.$i.'</a></li>';
}
if ($current_page < $total_page && $total_page > 1){
echo '<li class="page-item"><a class="page-link" href="index.php?'.$link.'page='.($current_page+1).'">Next</a></li>';
}
?>
</ul>
</div>
result:
Fatal error
: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '-3, 3' at line 1 in C:\xampp\htdocs\webtintuc\incs\class_db.php:100 Stack trace: #0 C:\xampp\htdocs\webtintuc\incs\class_db.php(100): PDOStatement->execute() #1 C:\xampp\htdocs\webtintuc\post.php(30): dblib->get_list('SELECT * FROM p...') #2 C:\xampp\htdocs\webtintuc\index.php(8): include('C:\xampp\htdocs...') #3 {main} thrown in
C:\xampp\htdocs\webtintuc\incs\class_db.php
on line
100
The limit and start in an SQL query cannot be negative in any way. It is a number that is used for limiting the number of rows that should be returned by the SQL statement.
To be useful, the limit should always be an integer that is greater than zero. start should be any integer that is zero and up. It is refer to as the offset.
Your calculations are ending up producing a start that is set to -3. That will never work.
Make sure that you review your logic so that it does not produce a negative $start value.
You can quickly confirm my theory by calculating $start like this ...
$start = max(0, ($current_page - 1) * $limit);
This will ensure that the value will be 0 if your formula returns a negative value.
Bear in mind that this is not a permanent solution. You need to properly figure out the way you are computer the value of the $start value.
I got uncaught error in that line because I don't know what to put into the while() statement. I just want to make sure the syntax can display the data.
<?php
require_once 'core.php';
$valid['success'] = array('success' => false, 'messages' => array(), 'order_id' => '');
if($_POST) {
$orderDate = date('Y-m-d', strtotime($_POST['orderDate']));
$clientName = $_POST['clientName'];
$sql = "INSERT INTO orders (order_date, client_name, order_status) VALUES ('$orderDate', '$clientName', 1)";
$order_id;
$orderStatus = false;
if($connect->query($sql) === true) {
$order_id = $connect->insert_id;
$valid['order_id'] = $order_id;
$orderStatus = true;
}
// echo $_POST['productName'];
$orderItemStatus = false;
for($x = 0; $x < count($_POST['namaBahan']); $x++) {
while ($sql->fetch_row()) {
// add into order_item
$orderItemSql = "INSERT INTO order_item (order_id, id_bahan, kuantiti, jenis_kuantiti, harga_per_unit, jumlah, order_item_status)
VALUES ('$order_id', '".$_POST['namaBahan'][$x]."', '".$_POST['kuantiti'][$x]."', '".$_POST['jenisKuantiti'][$x]."','".$_POST['harga'][$x]."', '".$_POST['jumlahValue'][$x]."', 1)";
$connect->query($orderItemSql);
if($x == count($_POST['namaBahan'])) {
$orderItemStatus = true;
}
} // while
} // /for quantity
$connect->query($orderItemSql);
$valid['success'] = true;
$valid['messages'] = "Successfully Added";
$connect->close();
echo json_encode($valid);
}
Can somebody help me to solve that statement in that line?
Fatal error: Uncaught Error: Call to a member function fetch_row() on
string in C:\xampp\htdocs\inventori\php_action\createOrder.php:27
Stack trace: #0 {main} thrown in
C:\xampp\htdocs\inventori\php_action\createOrder.php on line 27
You need to store your result set post query call. And then utilize fetch_row on the result set, instead of your $sql string.
It should be like this:
$result = $connect->query($sql);
if($result) {
$order_id = $connect->insert_id;
$valid['order_id'] = $order_id;
$orderStatus = true;
}
// echo $_POST['productName'];
$orderItemStatus = false;
for($x = 0; $x < count($_POST['namaBahan']); $x++) {
while ($result->fetch_row()) {
Note: Your code is very much open to SQL Injection ! Use Prepared Statements.
Here is the error I keep getting:
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter
number: parameter was not defined in
C:\xampp\htdocs\premiumems\classes\Admin.php:89 Stack trace: #0
C:\xampp\htdocs\premiumems\classes\Admin.php(89):
PDOStatement->execute() #1 C:\xampp\htdocs\premiumems\process.php(60):
Admin->update(Array, '1') #2 {main} thrown in
C:\xampp\htdocs\premiumems\classes\Admin.php on line 89
public function update($fields, $id)
{
//$sql= UPDATE admin SET name = :name,
$st="";
$counter=1;
$total_fields=count($fields);
foreach($fields as $key=>$value)
{
if($counter===$total_fields)
{
$set="$key=:".$key;
$st=$st.$set;
}
else
{
$set="$key=:".$key.",";
$st=$st.$set;
$counter++;
}
}
$sql="";
$sql.= "UPDATE admin SET".$st;
$sql.= "WHERE admin_id =".$id;
$stmt=$this->connection()->prepare($sql);
foreach ($fields as $key => $value)
{
// code...
$stmt->bindValue(':' .$key, $value);
}
$stmtexec=$stmt->execute();
if ($stmtexec)
{
// code...
$reply = "employee updated successfully";
$_SESSION['success']=$reply;
header('location:index.php');
}
else
{
// code...
$reply = "unable to update employee, try again later";
$_SESSION['failure']=$reply;
header('location:edit.php?staffid='.$admin_id);
}
} //function used for updating files
The class handling the update process above.
think you should try this code below.
public function update($fields, $id)
{
//$sql= UPDATE admin SET name = :name,
$fields = (array) $fields;
if ( count($fields) > 0)
{
// update
$total = count($fields);
$keys = array_keys($fields);
$values = array_values($fields);
$set = "SET ";
$dataParams = [];
// Handle keys
if ($total == 1)
{
$set .= $keys[0] .' = :'.$keys[0];
$dataParams[':'.$keys[0]] = $values[0];
}
else
{
foreach ($keys as $i => $key)
{
$set .= $key .' = :'.$key . ', ';
$dataParams[':'.$key] = $values[$i];
}
}
$set = rtrim($set, ', ');
$sql = "UPDATE admin {$set} WHERE admin_id = {$id}";
$stmt = $this->connection();
$stmt->prepare($sql);
$execute = $stmt->execute($dataParams);
// should work fine here.
var_dump($execute);
}
else
{
return false;
}
}
I am inserting multiple rows from one submit button by the usage of array. Insertion of records is working smoothly. Now I want to stop insertion of data if record is already existed. My syntax for single record updating is works to prevent multi-insertion of same record. But I am confused and can't get idea while using array. I've tried a lot, but every method display error.
This code is working.
if(isset($_POST['submit'])){
$number = $_POST['number'];
$letter = $_POST['letter'];
$sql = "INSERT INTO class(number, letter) VALUES(:number, :letter)";
$query = $con->prepare($sql);
foreach($number AS $key => $n){
$query->bindParam(':number', $number[$key]);
$query->bindParam(':letter', $letter[$key]);
$query->execute();
}
}
My intention is to stop insertion of data if it is already inserted. So I tried like this. I am sure it is wrong because array variable can't pass to first syntax**(sql1)** and $query is not being accessed to foreach clause. I have no idea, So I used like this. Please provide me any idea to stop already inserted record.
I want to change in this code
<?php
if(isset($_POST['submit'])){
$number = $_POST['number'];
$letter = $_POST['letter'];
$sql1 = 'SELECT COUNT(*) FROM class WHERE number = :number';
$stmt = $con->prepare($sql1);
$stmt->bindParam(':number', $number[$key]);
$stmt->execute();
if($stmt->fetchColumn()){
echo"<script>alert('Class is already existed')</script>";
}
else{
$sql = "INSERT INTO class(number, letter) VALUES(:number, :letter)";
$query = $con->prepare($sql);
}
foreach($number AS $key => $n){
$query->bindParam(':number', $number[$key]);
$query->bindParam(':letter', $letter[$key]);
$query->execute();
}
}
?>
This code displays following error
Notice: Undefined variable: key in C:\xampp\htdocs\marksheet\class.php on line 53
Notice: Undefined variable: query in C:\xampp\htdocs\marksheet\class.php on line 57
Fatal error: Uncaught Error: Call to a member function bindParam() on null in C:\xampp\htdocs\marksheet\class.php:57 Stack trace: #0 {main} thrown in C:\xampp\htdocs\marksheet\class.php on line 57
This should work:
if (isset($_POST['submit'])) {
if(!empty($_POST['number']) && !empty($_POST['letter']) )
{
$number = $_POST['number'];
$letter = $_POST['letter'];
// Assuming both $number and $letter 1 dimensional array with equal number of indexes
$notInsertedKey = [];
foreach ($number AS $key => $item) {
/* Checking Existence*/
$sql1 = 'SELECT COUNT(*) as counted FROM class WHERE number = :number';
$stmt = $con->prepare($sql1);
$stmt->bindParam(':number', $number[$key]);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);
if ($data['counted'] < 1) {
// echo "Not Exist";
$sql = "INSERT INTO class(number, letter) VALUES (:number, :letter)";
$query = $con->prepare($sql);
$query->bindParam(':number', $number[$key]);
$query->bindParam(':letter', $letter[$key]);
$query->execute();
} else {
$notInsertedKey[] = $key;
// Incase you want to know the failed indexes.
echo "<script>alert('Class is already existed')</script>";
}
}
}
}
UPDATE
Solution suggested by #AlivetoDie works well as shorthand way to insert unique data and drop the duplicated one. However, it doesn't have any means to track the failed data indexes since the query always returns TRUE.
I would like to recommend following way. First of all you need a dynamic function which should check record in the relevant table
function isExist($columnName, $columnValue, $tableName){
$columnName = (!empty($columnName)) ? $columnName : 'empty';
$columnValue = (!empty($columnValue)) ? $columnValue : 'empty';
$tableName = (!empty($tableName)) ? $tableName : 'empty';
$exist = 0;
if($columnName != 'empty' && $columnValue != 'empty' && $tableName != 'empty'){
$sql = "select * from `".$tableName."` where `".$columnName."` = '".$columnValue."'";
$isExist = mysqli_query($this->connection,$sql);
if(mysqli_num_rows($isExist) > 0){
$exist = 1;
}
}
return $exist;
}
Then use it in your function by following way
if(isset($_POST['submit'])){
$error = 0;
$response = array();
$number = $_POST['number'];
$letter = $_POST['letter'];
$number_name_exist = $this->isExist('number', $number, 'class');
if($number_name_exist == 1){
$error = 1;
$response['error'] = $number . ' is already exists';
}
if($error == 0){
$sql = "INSERT INTO class(number, letter) VALUES(:number, :letter)";
$query = $con->prepare($sql);
foreach($number AS $key => $n){
$query->bindParam(':number', $number[$key]);
$query->bindParam(':letter', $letter[$key]);
$query->execute();
}
}
}
In the above example you can see there $error variable and $response array which will be make your script more dynamic and you can prevent duplicate insertion and also you can check multiple columns.
i am beginner in php . and i have this Sql problem:
function InsertUserBirdsFromFile($File_content){
for($i =0; $i < count($File_content); $i+=2){
$id = $this->Master_file($File_content[$i], $File_content[$i + 1] );
if(isset($id)){
try{
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'.$id .') ";
$result = mysql_query($qry,$this->connection);
}
catch(Exception $ex){ echo $ex;}
}
}
}
function Master_file($name, $latin ){
try{
$qry = "SELECT tax_id FROM master where name =".$name." and latin =".$latin;
$result = mysql_query($qry,$this->connection);
}
catch(Exception $ex){ return null;}
if ($result == true && mysql_num_rows($result) >0) {
$p=0;
while ($Res_user = mysql_fetch_array($result) ) {
$marques[$p] = $Res_user;
$p++;
}
return $marques[0]['tax_id'];
}
else return null;
}
the error shown is : Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home/admin/public_html/hitlist/include/fg_membersite.php on line 427
in this line $result = mysql_query($qry,$this->connection);.
what is the problem? How can i fix it?
Well, maybe unrelated but i think this needs to be fixed
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'.$id .') "
to
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,".$id .") "
or
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,$id) "