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;
Related
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
Low level question but, I understand that you can select elements from a table using:
$sql = "SELECT blah FROM TABLE WHERE this = 'something' ";
But when I try to select a specific value from my table, where let's say a user has no tries left so if I try to grab how many tries they have left with:
$sql = "SELECT tries FROM table WHERE user = 'something'";
How would I grab that value specifically if it was 5 or 9? I tried setting a variable equal to something I $sql off my table but it doesn't grab the value.
Edit
I have a database that has a table called Item which contains: id, name, value, and stock of a particular item. If a user wants to order that item I will first check it if's in stock with a function, to see if it is not in stock then a error message is printed, otherwise accept the order.
Extremely primitive since I'm just trying to get grab the stock value first.
$query = $_GET['query']; //id I get from the specified item
echo 'the id is: ' .$query.''; //test purposes
$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error connecting to database server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname");
$sql1 = "SELECT item_stock FROM chat-db.Item WHERE id = '".$query."'";
echo '' .$sql2. ''; //test purposes
whats the correct way to assign the value from that specific stock to a variable?
If you want to grab rows with a set of possible values you can use 'IN' such as:
Get all columns from users table where users have 5 or 9 tries:
SELECT * FROM users WHERE tries IN('5', '9'); or
If you want to select where the user has no tries left, assuming the tries column is a numeric type you can look for rows with 0 tries:
Get all columns from Item table where stock is 0:
SELECT * FROM db_inv.Item WHERE stock = '0';
Get all columns from users table where tries is 0:
SELECT * FROM users WHERE tries = '0';
As for your php code you should be able to do the following:
$query = $_GET['query']; //id I get from the specified item
echo 'the id is: ' . $query; //test purposes
$mysql_handle = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Error connecting to database server");
$sql1 = "SELECT item_stock FROM chat-db.Item WHERE id = '".$query."'";
$results = mysqli_query($mysql_handle, $sql1);
if (!empty($results) && mysqli_num_rows($results) > 0) {
while($rec = mysqli_fetch_array($results)) {
echo $rec['item_stock'];
}
}
I have 2 MYSQL tables and when I pick up dates from table A which contains only 1 column and lets say 10 rows with dates
$result = mysql_query("SELECT * FROM A");
$row = mysql_fetch_assoc($result);
And after I want to UPDATE another table B with using this dates from table A mysql_query("UPDATE B SET something='1' WHERE name='".$row['name']."'")
So i need to update the second table, but its updating just once with first date from table A, and other 9 its ignoring. So my question is, how to make updating of second table with each date from 1 table?
You need to run a the updates in a loop. After executing your query
$result = mysql_query("SELECT * FROM A");
and verifying that it has succeeded (make sure $result is not null), instead of fetching one row, use a loop:
while($row = mysql_fetch_assoc($result)){
// perform calculations & assignments with the $row elements
$result2 = mysql_query("UPDATE B SET something='1'
WHERE name='".$row['name']."'");
if(! $result2){
echo "update failed";
}
// Any other stuff you need to do
}
Alternatively:
If the something in the update is the same for all the rows, you can change your first query to give you a coma-separated string of names:
$result = mysql_query("SELECT CONCAT("'",GROUP_CONCAT(name SEPARATOR "','"),"'")
AS all_names FROM A");
This way, you receive only one row, and you can then use it in your second query:
$result2 = mysql_query("UPDATE B SET something='1'
WHERE name IN (".$row['name'].")");
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
I have this query :
INSERT INTO db1.outbox (DestinationNumber, TextDecoded)
SELECT User.CellPhone, '$SMSMessage' as TextDecoded
FROM db2.User
WHERE User.PurchaseDate BETWEEN 2012-01-01 AND 2012-01-31
it does multiple rows insertion to 'outbox' table. but I don't know how many rows inserted. how to have number of rows inserted from that SQL syntax? thanks.
update
I got '-1' as result of this command :
$insertedRows = mysql_query("SELECT ROW_COUNT()");
$rowInserted = mysql_fetch_array($insertedRows);
$rowInserted = $rowInserted[0];
echo $rowInserted;
but I see there are 27 rows inserted on my table. what did I do wrong?
put this on your last statement;
SELECT ROW_COUNT();
UPDATE 1
how about using mysql_affected_rows, example
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
/* this should return the correct numbers of deleted records */
mysql_query('you SQL QUERY HERE');
printf("Records deleted: %d\n", mysql_affected_rows());
?>
Here are some possibilities:
» If you have an AUTO_INCREMENT column, you can fetch the row number before and after insert
» SELECT ROW_COUNT() returns the number of rows changed, deleted, or inserted by the last statement if it was an UPDATE, DELETE, or INSERT (doc)
» You can use mysqli_affected_rows (since mysql_ functions are being deprecated) to get the number of affected rows in a previous MySQL operation (doc)
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
if (!$link) {
printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
exit();
}
/* Insert rows */
mysqli_query($link, "INSERT INTO myTable VALUES (1)");
printf("Affected rows (INSERT): %d\n", mysqli_affected_rows($link));