I have one table name Blog and i insert data on the table by using tne next query
INSERT INTO `blog`(title,desc) VALUES ('blog1','description')
And then i select data from the table by using
SELECT * FROM `blog`
This gives two hit to the database. Is there any possible way to do both queries at the same time. I want to make the process with one hit to the database.
i suppose you can use below statement :
INSERT INTO blog(title,desc) VALUES ('blog1','description') SELECT *
FROM blog ;
Here is the document
https://www.php.net/manual/en/mysqli.quickstart.multiple-statement.php
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
do {
if ($res = $mysqli->store_result()) {
var_dump($res->fetch_all(MYSQLI_ASSOC));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
?>
Related
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'm trying to run multiple queries on a MySQL server at the same time from PHP with the same database connection. I have run the SQL statement on the server itself but the response is as expected. I'm getting no SQL exceptions but just no SQL query response at all (the result is FALSE).
Is this because you can't query when another query is already active on the same connection?
The code loads data from the database table with people's names and last paid date information. This is displayed in a form and then the user can select members to update payments for. Then, the part I'm stuck on is the second query where the selected names are trying to find family_id for families.
Code snippet:
mysql_select_db($database_W3OITesting, $W3OITesting);
$yearnow = date("Y",strtotime('+1 year')).'-12-31';
$yearrecent = date("Y",strtotime('-1 year')).'-12-31';
$query_Recordset1 = "SELECT DISTINCT lname, fname, suffix, fcccall, members.member_id, MaxDateTime " .
"FROM members " .
"INNER JOIN " .
"(SELECT paid.member_id, MAX(paid.year) AS MaxDateTime " .
"FROM paid " .
"GROUP BY paid.member_id) groupedpaid ".
"ON members.member_id = groupedpaid.member_id " .
"Where (MaxDateTime < '$yearnow') AND ".
"(MaxDateTime >= '$yearrecent')" .
"ORDER BY lname, fname, suffix, fcccall";
$Recordset1 = mysql_query($query_Recordset1, $W3OITesting) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
//if a post is received handle it here
function getPostArray($array){
foreach ($array as $key => $value){
//search here for if this member is part of a family
//if not part of a family just update the payment
//record for the member with the value
try {
$query_Recordset3 = "SELECT lname, fname, suffix, `members`.member_id , `family`.member_id " .
"FROM members, family " .
"WHERE (`members`.member_id = `family`.member_id " .
"AND `members`.member_id = $key)";
echo $query_Recordset3. "<br>";
$Recordset3 = mysql_query($query_Recordset3, $W3OITesting);
$row_Recordset3 = mysql_fetch_assoc($Recordset3);
$totalRows_Recordset3 = mysql_num_rows($Recordset3);
echo $totalRows_Recordset3 . "<br>";
echo "$key => $value";
if($totalRows_Recordset3==FALSE) {//Recordset3 is always FALSE
echo " Error - " . $row_Recordset3['lname'];
}
if($totalRows_Recordset3!=0) {
echo " - A Family";
} else {
echo " - Individual";
}
echo "<br>";
}
catch(Exception $e)
{
echo "Exception: $e";
die();
}
if(is_array($value)){ //If $value is an array, get it also
getPostArray($value);
}
}
}
Im trying to rewrite mysql_ into mysqli_, but got 2 errors
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
and
mysqli_num_rows() expects parameter 1 to be mysqli_result,
why? Ive fixed mysql_query("SELECT...) into mysqli_query($db, "SELECT..) and all others
<?php
ob_start();
session_start();
include('config/configuration.php');
if($_POST['Login'])
{
$UserName=$_POST['username'];
$Password=md5($_POST['password']);
$UserQuery=mysqli_query($db, "SELECT Id, UserName, FirstName, LastName, Level FROM users WHERE UserName='$UserName' AND Password='$Password' AND IsActive=1 and level >= 3");
$UserDetails=mysqli_fetch_array($UserQuery);
if(mysqli_num_rows($UserQuery))
{
$_SESSION['UserName'] = $UserDetails['UserName'] . ' (' . $UserDetails['FirstName'] . ' ' . $UserDetails['LastName'] . ')';
$_SESSION['UserId'] = $UserDetails['Id'];
$_SESSION['Level'] = $UserDetails['Level'];
mysqli_query("UPDATE users SET NumberOfLogin = NumberOfLogin + 1, LastLoginDate = NOW() WHERE Id = " . $_SESSION['UserId'] . " ");
Your query is failing.
Try this to see the issue:
if (!$UserQuery) {
echo "MySQLi Error: " . mysqli_error($con);
die();
}
I have a site where I have a database for all accounts and whatnot, and another for storing actions that the user has done on the site.
Each user has their own table but I want to combine the data of each user group (all users that are "linked together") and order that data in the time the actions took place.
Here's what I have;
<?php
$query = "SELECT `TALKING_TO` FROM `nnn_instant_messaging` WHERE `AUTHOR` = '" . DISPLAY_NAME . "' AND `TALKING_TO` != ''";
$query = mysql_query( $query, $CON ) or die( "_error_ " . mysql_error());
if( mysql_num_rows( $query ) != 0 ) {
$table_str = "";
$select_ref_clause = "( ";
$select_time_stamp_clause = "( ";
while( $row = mysql_fetch_array( $query ) ) {
$table_str .= "`actvbiz_networks`.`" . $row['TALKING_TO'] . "`, ";
$select_ref_clause .= "`actvbiz_networks`.`" . $row['TALKING_TO'] . ".REF`, ";
$select_time_stamp_clause .= "`actvbiz_networks`.`" . $row['TALKING_TO'] . ".TIME_STAMP`, ";
}
$table_str = $table_str . "`actvbiz_networks`.`" . DISPLAY_NAME . "`";
$select_ref_clause = substr($select_ref_clause, 0, -2) . ") AS `REF`, ";
$select_time_stamp_clause = substr($select_time_stamp_clause, 0, -2) . " ) AS `TIME_STAMP`";
}else{
$table_str = "`actvbiz_networks`.`" . DISPLAY_NAME . "`";
$select_ref_clause = "`REF`, ";
$select_time_stamp_clause = "`TIME_STAMP`";
}
$where_clause = $select_ref_clause . $select_time_stamp_clause;
$query = "SELECT " . $where_clause . " FROM " . $table_str . " ORDER BY TIME_STAMP";
die($query);
$query = mysql_query( $query, $CON ) or die( "_error_ " . mysql_error());
if( mysql_num_rows( $query ) != 0 ) {
}else{
?>
<p>Currently no actions have taken place in your network.</p>
<?php
}
?>
The code above returns the sql statement:
SELECT ( `actvbiz_networks`.`john_doe.REF`, `actvbiz_networks`.`Emmalene_Jackson.REF`) AS `REF`, ( `actvbiz_networks`.`john_doe.TIME_STAMP`, `actvbiz_networks`.`Emmalene_Jackson.TIME_STAMP` ) AS `TIME_STAMP` FROM `actvbiz_networks`.`john_doe`, `actvbiz_networks`.`Emmalene_Jackson`, `actvbiz_networks`.`act_web_designs` ORDER BY TIME_STAMP
I really am learning on my feet with SQL.
Its not the PHP I have a problem with (I can quite happily code away with PHP); It's just help with the SQL statement.
Any help much appreciated.
Didn't take the time to through your code, but from the question it sounds like you want UNION.
SELECT
3 AS a
UNION SELECT
2 AS a
UNION SELECT
1 AS a
ORDER BY a
Gives
a
=
1
2
3
EDIT: So perhaps something like this?
DROP TEMPORARY TABLE IF EXISTS t1;
DROP TEMPORARY TABLE IF EXISTS t2;
DROP TEMPORARY TABLE IF EXISTS tmp;
CREATE TEMPORARY TABLE t1 (
a INT(11)
);
CREATE TEMPORARY TABLE t2 (
b INT(11)
);
INSERT INTO t1 VALUES (1), (2), (3);
INSERT INTO t2 VALUES (4), (5), (6);
CREATE TEMPORARY TABLE tmp
SELECT
b AS f
FROM t2
UNION SELECT
a AS f
FROM t1
ORDER BY f;
SELECT * FROM tmp;
returns
f
=
1
2
3
4
5
6
Have you tried using a view? This way, you can use the UNION as simendsjo suggested and everything is in a single table. This is not exactly a temporary solution but a very nice, clean and efficient way of doing this.
I endeed up solving by using simendsjo's tips and used UNION ALL
<?php
$query = "SELECT `TALKING_TO` FROM `nnn_instant_messaging` WHERE `AUTHOR` = '" . DISPLAY_NAME . "' AND `TALKING_TO` != ''";
$query = mysql_query( $query, $CON ) or die( "_error_ " . mysql_error());
if( mysql_num_rows( $query ) != 0 ) {
while( $row = mysql_fetch_array( $query ) ) {
$table_str = 'SELECT REF, ACTION, TIME_STAMP, DATA, IMAGE, DISPLAY_NAME FROM actvbiz_networks.' . $row['TALKING_TO'] . ' UNION ALL ';
}
}else{
$table_str = "";
}
$table_str = $table_str . 'SELECT REF, ACTION, TIME_STAMP, DATA, IMAGE, DISPLAY_NAME FROM actvbiz_networks.' . DISPLAY_NAME . ' ORDER BY TIME_STAMP DESC';
$query = mysql_query( $table_str, $CON ) or die( "_error_ " . mysql_error());
if( mysql_num_rows( $query ) != 0 ) {
while( $rows = mysql_fetch_array( $query ) ) {
I'm trying to a single value in my DB...When I run it through the console, it works correctly (as I'm replacing the variables with numbers and text).. However, My query is not returning a value for book ID when I insert the PHP variable for it.. It's because the book_id is unpopulated...
$query = "UPDATE books "
. "SET readstatus='".$readstatus."' "
. "WHERE book_id=".$book_id;
echo $query
The echoed query states:
UPDATE books SET readstatus='half' WHERE book_id=0
The book ID is stored in the URI as bookstatusupdate.php?book_id=
Just cannot figure this one out!
It would help to know the error. Firstly, echo out the query:
$query = "UPDATE books "
. "SET readstatus='".$readstatus."' "
. "WHERE book_id=".$book_id;
echo $query;
I would guess that $book_id is unpopulated, so the query fails. What you should really be doing to make it secure is casting integers with (int) and wrapping strings in mysqli_real_escape_string().
$query = "UPDATE books "
."SET readstatus='". mysqli_real_escape_string( $readstatus )."' "
."WHERE book_id=". (int) $book_id;
If you're trying to get data from the URL, do it like so:
$book_id = (int) $_GET['book_id'];
$query = "UPDATE books "
."SET readstatus='". mysqli_real_escape_string( $readstatus )."' "
."WHERE book_id=". (int) $book_id;
echo $query;