I have two mysql queries to insert the data into two different tables. the result of the queries are as follows:
INSERT INTO table1 (ans1,ans2,ans3,ans4,ans5) VALUES (0,0,0,0,0),(1,1,1,0,0),(0,0,0,0,0)
INSERT INTO table2 (uid,cid,sid) VALUES (1,abc,123),(2,def,456),(3,ghi,789)
How can I concatenate these two results so that the output would look like
INSERT INTO table3 (uid,cid,sid,ans1,ans2,ans3,ans4,ans5)
VALUES
(1,abc,123,0,0,0,0,0),
(2,def,456,1,1,1,0,0),
(3,ghi,789,0,0,0,0,0)
I think something as this:
<?php
//First we need connect to database
$server = "localhost";
$Userdb = "admin";
$Passworddb = "password";
$database = "db";
$conn = mysqli_connect($server, $Userdb, $Passworddb, $database);
mysqli_set_charset($conn, "utf8");
//Getting values - for this example it is static
//For concate we need values as array => explode()
$colums1 = "ans1,ans2,ans3,ans4,ans5";
$values1 = explode("),(", substr("(0,0,0,0,0),(1,1,1,0,0),(0,0,0,0,0)", 1, -1));
$colums2 = "uid,cid,sid";
$values2 = explode("),(", substr("(1,abc,123),(2,def,456),(3,ghi,789)", 1, -1));
//Query for table1
$command = "INSERT INTO table1 (".$colums1.") VALUES ".$values1;
mysqli_query($conn, $command) or die(mysqli_error($conn));
//Query for table2
$command = "INSERT INTO table2 (".$colums2.") VALUES ".$values2;
mysqli_query($conn, $command) or die(mysqli_error($conn));
//We need to concate values so =>
//=> For every index of $values1 add at same index into $values3 concated $values1 and $values2
$values3 = array();
for ($x = 0; $x <= count($values1); $x++) {
$values3[$x] = "(".$values2[x].",".$values1[$x].")";
}
//Query for table3
$command = "INSERT INTO table3 (".$colums2.",".$colums1.") VALUES (".implode("),(", $values3).")";
mysqli_query($conn, $command) or die(mysqli_error($conn));
?>
I think that this SHOULD works (one never knows :) )
I have done this type of SELECT many times, but this time I can't get it to work. Any ideas, please?
$Name = "Dick";
$conn = mysqli_connect($server, $dbname, $dbpw, $dbuser);
$sql = "SELECT id FROM table WHERE $Name = table.first_name";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$customer_id = $row['id'];
Database::disconnect();
echo "customer id = " . $customer_id;
If you really DO have a table named table it would be more appropriate to use back ticks around the name since the word TABLE is a reserved word in MySQL. You should also use single quotes around your variable if it contains a string:
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
Other possible reasons if the query still doesn't work for you:
Make sure you have the connection parameters in the right order. It should be: mysqli_connect($server, $dbuser, $dbpw, $dbname).
You should be using fetch_array() instead of fetch_assoc() if you expect a one row result.
You are mixing PROCEDURAL STYLE with Object Oriented Style when using mysqli_connect() instead of mysqli(), at the same time using $result-> which is object oriented style. You should decide one style and stick with it.
This would be the procedural style of your query:
$Name = "Dick";
$conn = mysqli_connect($server, $dbuser, $dbpw, $dbname); // NOTE THE CHANGED ORDER OF CONNECTION PARAMETERS!
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$customer_id = $row['id']; // YOUR CUSTOMER ID
mysqli_free_result($result); // FREE RESULT SET
mysqli_close($conn); // CLOSE CONNECTION
And this would be the object oriented style:
$Name = "Dick";
$conn = new mysqli($server, $dbuser, $dbpw, $dbname);
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
$result = $conn->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
$customer_id = $row['id']; // YOUR CUSTOMER ID
$result->free(); // FREE RESULT SET
$conn->close(); // CLOSE CONNECTION
I would recommend naming your table something else than table since it's a reserved word and could get you into parsing problems. The same goes with field names. More reading: https://dev.mysql.com/doc/refman/5.5/en/keywords.html
More about mysqli_fetch_array() and differences in procedural style and object oriented style use: http://php.net/manual/en/mysqli-result.fetch-array.php
$sql = "SELECT id FROM table WHERE '$Name' = table.first_name";
You simply need to concat the variable like this:
$sql = "SELECT id FROM table WHERE " . $Name . " = table.first_name";
I am having a weird issue but I do not understand what is happening. I amcreated a function to update up to three columns (end_plan_date, balance and server) in a table (user) and 2 inserts in another table.
For some reason, my last update (column server of the user table) is not committed ($query = mysql_query("UPDATE user SET server='$serv' WHERE email='$subemail'");) unless I give a value for at leat one of the two other values ($subamt or $subday).
Do you know why this query is not updating the user table with the server value I parsed?
function addBalance($subemail, $subamt,$subday,$userid,$serv) {
$q = "SELECT * FROM user WHERE email = '$subemail'";
$result = mysql_query($q, $this->connection);
$dbarray = mysql_fetch_array($result);
$endplan_date=$dbarray['end_plan_date'];
if($subday >0){
if($endplan_date=="0000-00-00" ){
$endplan_date = date('Y-m-d');
$new_endplan_date = date('Y-m-d',strtotime($endplan_date . "+".$subday." days"));
}else{
$new_endplan_date = date('Y-m-d',strtotime($endplan_date . "+".$subday." days"));
}
$query = mysql_query("UPDATE user SET end_plan_date='$new_endplan_date' WHERE email='$subemail'");
$recdate=gmdate('Y-m-d H:i:s');
$q = "INSERT INTO com_gest(recdate,userid,type,recvalue) VALUES ('$recdate','$userid','Plan Date','$subday')";
mysql_query($q, $this->connection);
}
if($subamt >0){
$query = mysql_query("UPDATE user SET balance=balance+".$subamt." WHERE email='$subemail'");
$recdate=gmdate('Y-m-d H:i:s');
$q = "INSERT INTO com_gest(recdate,userid,type,recvalue) VALUES '$recdate','$userid','Balance','$subamt')";
mysql_query($q, $this->connection);
}
$query = mysql_query("UPDATE user SET server='$serv' WHERE email='$subemail'");
return 0;
}
In your code u can't get directly this
$endplan_date=$dbarray['end_plan_date'];
for fetching this variable u have to use while loop like
while($dbarray = mysql_fetch_array($result);) {
$endplan_date=$dbarray['end_plan_date'];
}
There was an issue when calling this function.
Bit of a noob when it comes to PDO. We have a a table that needs to be updated with a cron job daily. The idea is to query the table and for each "active = 1" get an integer from a duration column convert that into days, get the "expiration" column and the duration to the expiration and update the expiration.
I am not even close to getting this to work, I am trying to just get the basics for now. Return the duration which is in hours divide by 24 add that to the date column as days and update EACH row with the appropriate new time.
The problem is I do not know how to update each row with its own information. I have the code below, it updates each row but the new "expires" date ends up being the same even though the expires values are different.
static function cronSetFeatured(){
try{
$db = new PDO('mysql:host=127.0.0.1;dbname=mydb', 'dbuser', 'pw' );
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo $e->getMessage();
die();
}
$query = $db->query('SELECT * FROM featured_producers ');
$now = date('Y-m-d H:i:s');
while($r = $query->fetch(PDO::FETCH_OBJ)){
$duration = $r->duration;
$ddays = $duration / 24;
$date = $r->date;
$expires = date("Y-m-d", strtotime($date. " + ".$ddays." days"));
}
$sql = "UPDATE `featured_producers`
SET `expires`= ?
WHERE `id` != 0";
$q = $db->prepare($sql);
$q->execute(array($expires));
echo $expires.'<br>';
}
Well if you want to UPDATE each record on its own, that query need to be part of the loop body:
while($r = $query->fetch(PDO::FETCH_OBJ)){
//calculate expiration
$duration = $r->duration;
$ddays = $duration / 24;
$date = $r->date;
$expires = date("Y-m-d", strtotime($date. " + ".$ddays." days"));
//Get the id (needed for update)
$id = $r->id;
//updating
$sql = "UPDATE `featured_producers`
SET `expires`= ?
WHERE `id` != ?";
$q = $db->prepare($sql);
$q->execute(array($expires, $id));
echo $expires.'<br>';
}
In making database queries in Zend Framework 2, how should I be sanitizing user submitted values? For example, $id in the following SQL
$this->tableGateway->adapter->query(
"UPDATE comments SET spam_votes = spam_votes + 1 WHERE comment_id = '$id'",
\Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE
);
You can pass parameters when you execute..
$statement = $this->getAdapter()->query("Select * from test WHERE id = ?");
$result = $statement->execute(array(99));
$resultSet = new ResultSet;
$resultSet->initialize($result);
You can also pass them directly to the query method
$statement = $this->getAdapter()->query(
"Select * from test WHERE id = ?",
array(99)
);
$result = $statement->execute();
$resultSet = new ResultSet;
$resultSet->initialize($result);
Both will produce the query "Select * from test WHERE id = '99'"
If you want to use named parameters:
$statement = $this->getAdapter()->query("Select * from test WHERE id = :id");
$result = $statement->execute(array(
':id' => 99
));
$resultSet = new ResultSet;
$resultSet->initialize($result);
If you want to quote your table/field names etc:
$tablename = $adapter->platform->quoteIdentifier('tablename');
$statement = $this->getAdapter()->query("Select * from {$tablename} WHERE id = :id");
$result = $statement->execute(array(
':id' => 99
));