Mysql select and insert using prepared statement - mysql

My mysql query is working fine
INSERT INTO donor_location (pc_id)
SELECT id
FROM pc
WHERE postcode= ?
i.e gets the postcode id from a postcode table then inserts that id into donor_location table.
I am using mysqli and prepared statements
without the select part it would be quite easy - something like
$stmt = $mysqli->prepare("INSERT INTO donor_charity(
id) values (?)") ;
however I am completely lost about how to incorporate the select

What you do is almost the same, just changing the query bit.
To select all records from charity_donor where the id is 25, you would do the follwing query:
SELECT *
FROM donor_charity
WHERE id = 25
Now to query this, first you have to prepare it:
$stmt = $mysqli->prepare("
SELECT *
FROM donor_charity
WHERE id = ?
");
Now to loop over the results, you must bind the param, and execute the query.
$stmt->bind_param('d', 25 ); // First param means the type of the value you're
passing. In this example, d for digit.
$stmt->execute();
Then you setup an array to hold the data returned from the query,
$row = array();
stmt_bind_assoc($stmt, $row);
And now to loop over the returned data.
while ( $stmt->fetch () ) {
print_r($row); // Should now contain the column.
}
For documentation, see:
Prepare: http://www.php.net/manual/en/mysqli.prepare.php
Bind param: http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Execute: http://www.php.net/manual/en/mysqli-stmt.execute.php
Fetch: http://www.php.net/manual/en/mysqli-stmt.fetch.php

You need to use Bind_param after Prepare statement.
$sql = "INSERT INTO donor_charity(
id) values (?)
";
/* create a prepared statement */
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
/* bind parameters for markers */
$stmt->bind_param('ssssss', $id);
$id = '123456';
/* execute query */
$stmt->execute();

Hope this post helps, it's so simple.
http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertRecordsUsingPreparedStatement.htm

Related

get the last id of the query with pdo php [duplicate]

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

MySQL Select Count on VARCHAR in PERL

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

SQL - SELECT with WHERE statement return false despite present field in table

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'";

MySQL ROW_COUNT() not working

I have this query:
DELETE FROM c_email WHERE code = '67890' AND user_id = '2';
SELECT ROW_COUNT() AS row_1;
I want to get a field named row_1, with number of rows deleted, but it seems not to work...
You could use the not depricated $mysqli->affected_rows; as shown in this document
Returnvalue: An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records were updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.
And a small example from that same website.
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Insert rows */
$mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows);
$mysqli->query("ALTER TABLE Language ADD Status int default 0");
/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);
/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);
/* select all rows */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows);
$result->close();
/* Delete table Language */
$mysqli->query("DROP TABLE Language");
/* close connection */
$mysqli->close();
?>
this is using PDO.
assuming you can do some research, set up a PDO connection and be sure to specify this option:
$db = new PDO ($dsn,$user,$pass,array (
PDO::ATTR_EMULATE_PREPARES=>TRUE,
));
then, prepare and execute your statement. I don't know of any mysql command which actually selects deleted rows. you'll have to go for rowCount()
$stmt = $db->prepare("DELETE FROM c_email WHERE code = '67890' AND user_id = '2'");
$stmt->execute();
$count = $stmt->rowCount();
But you want to select a second query in the same call so we'll do it with normal selecting of existing rows
$stmt = $db->prepare(
'UPDATE c_email SET code=1376 WHERE user_id=3;
SELECT user_id FROM c_email WHERE code=1376;'
);
$stmt->execute(); // this executes both statements, and sets some internal pointer towards the first.
$stmt->nextRowset(); // it's the next one that interests us
$row = $stmt->fetch(PDO::FETCH_ASSOC); // let's get the value
echo $row['user_id'];
START TRANSACTION;
SELECT #before:=(SELECT count() FROM c_email);
DELETE FROM c_email WHERE code = '67890' AND user_id = '2';
SELECT #after:=(SELECT count() FROM c_email);
COMMIT;
SELECT #before-#after AS DELETED;

Resource Id #22 inserted into database field

I'm having a problem with running this function. When it runs, it does exactly what I want, except that within my like_requests table the request_id is not the mysql query result linked to the variable $select but Resource Id #22. I thought that resource id's appear when you are trying to echo out a result, but I'm not using echo. What's wrong with the code?
function update_likes($band_requested, $new_likes, $session_user_id) {
$select = mysql_query("SELECT `primary_id` FROM `requests` WHERE
`user_requester_id` = '$session_user_id' AND `person_requested` =
'$band_requested'");
$sql_2 = "INSERT INTO `like_requests` (user_id, request_id) VALUES
('$session_user_id', '$select')";
mysql_query($sql_2);
}
$band_requested = 'rally done';
$new_likes = 239;
$the_session_user_id = 3;
update_likes($band_requested, $new_likes, $the_session_user_id);
UPDATE WITH CORRECTED ANSWER
Here is the code corrected with help from David.
function update_likes($band_requested, $new_likes, $session_user_id)
{
$select = mysql_query("SELECT `primary_id` FROM `requests` WHERE `user_requester_id` =
'$session_user_id' AND `person_requested` = '$band_requested'");
$row = mysql_fetch_row($select);
$request_id = $row[0];
$sql_2 = "INSERT INTO `like_requests` (user_id, request_id) VALUES ('$session_user_id',
'$request_id')";
mysql_query($sql_2);
}
mysql_query returns a resource (http://php.net/manual/en/function.mysql-query.php) not just a scalar value. You'd need to use a function like mysql_fetch_row() to get the, presumably, one row you want, assign that row to a variable $row, then retrieve the primary_id with array syntax like $row['primary_id']. By the way, apparently mysql_query is being eased out and we should use the MySQLi API with the mysqli_query() method.