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));
Related
My teacher table is like:'
I have a teacher attendance table with data like as shown below:-
I'm trying to write codes which when executed will populate an excel file in the format given below. Where A= Absent, P= Present and, S= Sunday.
Logic for Present (P) : For any given date if ta_clock_in_tm & ta_clock_out_tm both are present then it's P.
Logic for Absent (A) : If no records exist for dates of the month in the teacher attendance table then it's A.
I also want to mark Sundays as S and calculate Total Present days and absent days.
I have not done anything like this before. I'm really confused about the sql query. Are both my tables enough to meet my requirement??
function export_to_mwiseallattenexcel($mnth)
{
$columnHeader ='';
$setData='';
$currYr = date("Y");
$noDaysInGvnMonth = cal_days_in_month(CAL_GREGORIAN, $mnth, $currYr);
$columnHeader = "Sl No"."\t"."Emp Name"."\t";
for($i=1; $i<=$noDaysInGvnMonth; $i++)
{
$columnHeader .= $i."\t";
}
$columnHeader .= "Total Working Days"."\t"."Total Absent"."\t"."Total Present"."\t"."Remarks"."\t";
$sql="";//<---WHAT TO WRITE HERE?????
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$rowData = '';
foreach($row as $value)
{
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData)."\n";
}
}
header("Content-Encoding: UTF-8");
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=Attendance_as.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader)."\n".$setData."\n";
}
Please help me with the SQL query. Thanks.
Open a connection to your server. There you can query EVERY command you want:
The code is:
try {
$sql = new PDO('mysql: host=localhost:3306; dbname=dbname', 'user', 'pwd');
$sql->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = "do something";
$sql -> query($statement)
} catch(PDOException $e) {
echo 'Connection failed: (f) ' . $e->getMessage();
}
Some interesting commands are:
CREATE TABLE table (any datatypes); -> creates new table
INSERT INTO table () VALUES (value1),(value2); -> fills table with values
ALTER TABLE table CHANGE old_name new_bane datatype; -> change table
ALTER TABLE table DROP COLUMN user_id; -> drops a column from a database
DELETE FROM table WHERE condition; -> delete all values where condition is true
UPDATE table SET data=value WHERE condition; updates values inside a table where condition is true
I have a table with 4 rows, I need to multiply col. 1 and 2 and put the results in col. 1 in the 2nd table. do the same with the other two cols' from table 1.
I'm sure its simple code. I just don't know MySQL
Get the values fetch the rows and insert again to the table 2:
$mysqli = new mysqli('127.0.0.1', 'tu_usuario', 'tu_contraseña', 'sakila');
if ($mysqli->connect_errno) {
echo "Errno: " . $mysqli->connect_errno . "\n";
echo "Error: " . $mysqli->connect_error . "\n";
exit;
}
$sql = "SELECT column1, column2 FROM table1";
if ($result = $mysqli->query($sql)) {
/* fetch object array */
while ($row = $result->fetch_row()){
$sql2 = "INSERT INTO table2 (col1) VALUES(".$row['column1']*$row['column2'].");";
$result = $mysqli->query($sql);
}
}
I didn't check if there is any error in theses code, it's just an example that shows the idea. I hope will be enough for you the explanation. If you still having doubts please answer again.
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;
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