I tried this function does not work me.
$clv = Execute("SELECT `id_propiedades` FROM `propiedades` WHERE `gestor`=2 ORDER BY `propiedades`.`id_propiedades` ASC");
$estado = "1";
foreach (array($clv) as $valor) {
$row_data[] = "('$valor','$estado')";
}
$sInsertSql3 = " INSERT INTO `cuotas` (`clv_cuota` ,`estado`) VALUES".implode(',', $row_data);
$GLOBALS["conn"]->Execute($sInsertSql3);
I get this error: Catchable fatal error: Object of class mysqlt_driver_ResultSet could not be converted to string in ...
any suggestions
I would try the single query:
'INSERT INTO cuotas (cuotas.clv_cuoata, cuotas.estado) SELECT propiedades.id_propiedades, 1 FROM propiedades WHERE gestor=2 ORDER BY propriedades.id_propiedades ASC'
Related
So, what am i doing wrong?
This query:
$query = "INSERT INTO table1 (art_nr, article, balance, list_type)
VALUES('$art_nr', '$article', '$balance', '$list_type')
ON DUPLICATE KEY UPDATE balance = sum(balance + '$quantity_ordered');
UPDATE table2 SET list = 'History' WHERE id = '$id'";
Will give me this error:
Failed to run query: SQLSTATE[HY000]: General error: 1111 Invalid use
of group function
This query:
$query = "INSERT INTO table1 (art_nr, article, balance, list_type) VALUES('$art_nr', '$article', '$balance', '$list_type')
ON DUPLICATE KEY UPDATE balance = sum(balance + '$quantity_ordered') WHERE art_nr = '$art_nr';
UPDATE table2 SET list = 'History' WHERE id = '$id'";
Will give me this error:
Failed to run query: 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 'WHERE art_nr = 'S2Bygel'; UPDATE purchase_orderlist SET
list' at line 2
UPDATE
This was my first query. With Params:
//SECURITY
$params_array= array(
':id' => $_POST['formData']['id'],
':art_nr' => $_POST['formData']['art_nr'],
':article' => $_POST['formData']['article'],
':quantity_ordered' => $_POST['formData']['quantity_ordered'],
':list_type' => $_POST['formData']['list_type']
);
//QUERY
$query = "INSERT INTO table1 (art_nr, article, balance, list_type) VALUES (:art_nr, :article, :balance, :list_type)
ON DUPLICATE KEY UPDATE balance = balance + VALUES(:quantity_ordered) WHERE art_nr = :art_nr;
UPDATE table2 SET list = 'History' WHERE id = :id";
The problem with this query is that im running two querys at the same time. and then i will get this error:
Failed to run query: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
SUCCESS
I had to use prepared statements and separate my two querys:
//SECURITY
$params_array= array(
':art_nr' => $_POST['formData']['art_nr'],
':article' => $_POST['formData']['article'],
':quantity_ordered' => $_POST['formData']['quantity_ordered'],
':list_type' => $_POST['formData']['list_type']
);
//QUERY
$query = "INSERT INTO table1
(art_nr, article, balance, list_type)
VALUES (:art_nr, :article, :quantity_ordered, :list_type)
ON DUPLICATE KEY UPDATE
art_nr = art_nr, article = article, balance = balance + :quantity_ordered, list_type = list_type";
//EXECUTE
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($params_array);
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
//SECURITY
$params_array= array(
':id' => $_POST['formData']['id']
);
//QUERY
$query = "UPDATE table2 SET list = 'History' WHERE id = :id";
//EXECUTE
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($params_array);
echo "success";
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
You just want to add the value of $quantity_ordered to balance for the row? Then you don't need the sum() aggregation function. Just the + operator is enough.
But it seems like you're doing this in a host language like PHP. You should urgently learn to use parameterized queries! Do not use string concatenation (or interpolation) to get values in a query. That's error prone and may allow SQL injection attacks against your application.
I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.
I know that I have to use this statement:
LAST_INSERT_ID()
That statement works with a query like this:
$query = "INSERT INTO `cell-place` (ID) VALUES (LAST_INSERT_ID())";
But if I want to get the ID using this statement:
$ID = LAST_INSERT_ID();
I get this error:
Fatal error: Call to undefined function LAST_INSERT_ID()
What am I doing wrong?
That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().
Like:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
Like this $lid = $conn->lastInsertId();
Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php
I have a simple SELECT statement:
$sql = "SELECT count(*) FROM member_temp WHERE member_Id = '".trim($id)."'";
The member_Id column is a VARCHAR(25) NOT NULL
This works fine until the SELECT gets to a member_Id that has a alpha value behind it, like 1126A. It then throws the error
Could not prepare SQL statement:SELECT count(*) FROM member_temp WHERE member_Id = '1126A'
As a test I remove this record and the SELECT runs fine until the next value with an A.
How can I make this query run and process records with an alpha character?
This is part of larger block of code that deletes records not found from the main member table:
while ( #data = $sth->fetchrow_array() ) {
my $id = $data[2];
my $pk = $data[0];
$sql = "SELECT count(*) FROM member_temp WHERE member_Id = '" . trim($id) . "'";
#print "$sql\n";
my $xth = $dbh->prepare($sql);
$xth->execute();
$cRows = $xth->fetchrow_array() || die "Could not prepare SQL statement:$sql";
#print "$cRows\n";
if ( $cRows == 0 ) {
$sql = "DELETE FROM member WHERE sys_Id = " . $pk;
$xth = $dbh->prepare($sql);
$xth->execute();
$cnt_del++;
}
Ok, this is Perl answer now :)
There is nothing wrong with your query (except that it is not preparing statements correctly and you are using string interpolation).
In the comments you said if this query is run directly
It completes successfully and returns a value of 0
Then in your code you have one condition which is wrong
$cRows = $xth->fetchrow_array() || die "Could not prepare SQL statement:$sql";
That means even if the query executed correctly but has 0 rows, it should show you that error message, which is not right.
So all you need to do is to fix that error message. That die should be shown if the query failed to execute, not when it executed correctly but has no results.
You can correct your query like
$sql = "SELECT count(*) FROM member_temp WHERE member_Id = ?";
$xth = $dbh->prepare($sql);
$xth->execute($id) or die("Failed to execute query:". $xth->errstr);
And your rows check can be
if ($xth->rows == 0)
// No match found
I am very confused about this (returning false):
$sql = "SELECT * from tbl_user WHERE group = 'abc'";
$res = mysql_query($sql);
if(mysql_num_rows($res) > 0) {
$response = array('status' => '1');
} else {
$response = array('status' => '0'); // ---> what I get back
die("Query failed");
}
...despite the fact the field group is present in mySQL database. Even more strange is that the following return the value of group:
$SQL = "SELECT * FROM tbl_user";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['group']; // ---> returns 'abc'
When I execute a WHERE clause with every other fields of my table excepting group (for example WHERE name = 'ex1' AND ID=1 AND isAllowed=0 (and so on...), everything is fine. As soon as I insert group = 'abc', I get nothing...
This makes me mad. If anyone could help... (I am running a local server with MAMP).
Thanks a lot!
The issue is that group is a reserved word in SQL.
For MySql you need to escape it with backticks
`group`
So your query would be
$sql = "SELECT * from tbl_user WHERE `group` = 'abc'";
Following this following example...
public function insert($model,$brand,$price){
mysql_query("INSERT INTO autos (model, brand, price) VALUES ($model,'$brand', $price)",$this->link);}
$conexion-> insert(05,"Ford",50000000);
...I made a modify/update code:
public function modify($model,$brand,$price,$newbrand,$newprice){
mysql_query("UPDATE 'crautos'.'autos' SET 'brand' = '$newbrand',
'price' = '$newprice' WHERE 'autos'.'model' =5 AND 'autos'.'brand' = '$brand' AND 'autos'.'price' ='$price' LIMIT 1) VALUES ($newbrand, $newprice)",$this->link);}
$conexion-> modify("Mitsubishi", 40000000);
But it didn't work, this is the error output:
Warning: Missing argument 3 for MyDataBase::modify(), called in on
line 15 Warning: Missing argument 4 for MyDataBase::modify(), called
in on line 28 and defined in on line 15 Warning: Missing argument 5
for MyDataBase::modify(), called in on line 28 and defined in on line
15 AND undefined variable newprice, newbrand, price. THE Insert code
is fine, and the modify code is causing the issue.
Here's the full code:
<?php
class MyDataBase{
private $link;
public function __construct($server,$user,$password,$base){
//Conectar
$this->link = mysql_connect($server,$user,$password);
mysql_select_db($base,$this->link);
}
public function insert($model,$brand,$price){
mysql_query("INSERT INTO autos (model, brand, price) VALUES ($model,'$brand', $price)",$this->link);}
public function modify($model,$brand,$price,$newbrand,$newprice){
mysql_query("UPDATE 'crautos'.'autos' SET 'brand' = '$newbrand',
'price' = '$newprice' WHERE 'autos'.'model' =5 AND 'autos'.'brand' = '$brand' AND 'autos'.'price' ='$price' LIMIT 1) VALUES ($newbrand, $newprice)",$this->link);}
public function __destruct(){
//desconectar
}
}
$conexion = new MyDataBase ('localhost', 'root', '','crcars');
$conexion-> insert(05,"Ford",50000000);
$conexion-> modify("Mitsubishi", 40000000);
?>
There is an invalid syntax in the update query. You do no need the VALUES part. Here is how it should be:
mysql_query("UPDATE 'crautos'.'autos' SET 'brand' = '$newbrand', 'price' = '$newprice' WHERE 'autos'.'model' =5 AND 'autos'.'brand' = '$brand' AND 'autos'.'price' ='$price' LIMIT 1");
Your UPDATE syntax is invalid, like #Martin pointed out, also you're calling modify() with two parameters, but the function is expecting 5. Add the extra values to $conexion-> modify("Mitsubishi", 40000000);
Something like:
$conexion-> modify("Mitsubishi", 40000000, $price, $newbrand, $newprice);