Mysqli second query doesn't work - mysqli

I want to use de result from my first query to insert in a second query, there's not error in the sintaxis.
I've been reading a lot but anything seems to work.
HELP!!!!
$sql = "CALL sp_producto(1);";
$rs = $mysqli->query($sql);
$idNuevo;
if ($fila = $rs->fetch_assoc()) {
$idNuevo = $fila['idNew']; //recupera el id del insertado
$talleres = explode(",", $_POST["proceso_prod"]);
foreach ($talleres as $t) {
//THIS DOESN'T WORK BUT IDONT KNOW WHY
$sql = "INSERT INTO proceso_produccion () VALUES (" . $idNuevo . ", ".$t.")";
echo $sql;
$mysqli->query($sql);
}
}

INSERT INTO proceso_produccion () VALUES (" . $idNuevo . ", ".$t.")
This line is the issue, if you are inserting values in all of your table columns no need to have this ()
,change your code to this :
INSERT INTO proceso_produccion VALUES (" . $idNuevo . ", ".$t.")
but if you are inserting to only certain column, you have to specify the column names,
like this :
INSERT INTO proceso_produccion ('firstColumn','anotherColumn') VALUES (" . $idNuevo . ", ".$t.")

Niang answered right, but also check if both values you are entering are integers. Otherwise, the should be in quotes like so:
INSERT INTO proceso_produccion ('firstColumn','anotherColumn') VALUES ('" . $idNuevo . "', '".$t."')
Also, this condition is not a real condition:
if ($fila = $rs->fetch_assoc()) {
You are only assigning value to $fila this way. It should be:
if ($fila == $rs->fetch_assoc()) {
Finally, if query still doesn't work can you please post echoed query, the result of echo $sql.

Related

How to loop through a list in a M query?

I have a query in PowerQuery editor, which brings all projects in an Azure DevOps organization:
let
Source = OData.Feed("https://analytics.dev.azure.com/someorg/_odata/v3.0-preview/Projects", null, [Implementation="2.0", OmitValues=ODataOmitValues.Nulls, ODataVersion=4]),
ProjectName = Source[ProjectName]
in
ProjectName
Also, I have this OData query which brings back all tasks for a single project:
let
Source = OData.Feed ("https://analytics.dev.azure.com/someorg/{project}/_odata/v3.0-preview/WorkItems?"
&"$filter=WorkItemType eq 'User Story' "
&"and State ne 'Closed' "
&"and startswith(Area/AreaPath,'{areapath}') "
&"&$select=WorkItemId,Title,WorkItemType,State,Priority,Severity,TagNames,AreaSK "
&"&$expand=AssignedTo($select=UserName),Iteration($select=IterationPath),Area($select=AreaPath), "
&"Links( "
&"$filter=LinkTypeName eq 'Related' "
&"and TargetWorkItem/WorkItemType eq 'User Story'; "
&"$select=LinkTypeName; "
&"$expand=TargetWorkItem($select=WorkItemType,WorkItemId,Title,State) "
&") "
,null, [Implementation="2.0",OmitValues = ODataOmitValues.Nulls,ODataVersion = 4])
in
Source
I need to run the second query once per each project in the first list, and append them in a single table, replacing {project} for each element. Is this possible in PowerQuery?
Thanks in advance;
Create a custom function where result will be your table
In your case something like:
query name is GetDataForProject
(project) =>
let
Source = OData.Feed ("https://analytics.dev.azure.com/someorg/{" & project & "}/_odata/v3.0-preview/WorkItems?"
&"$filter=WorkItemType eq 'User Story' "
&"and State ne 'Closed' "
&"and startswith(Area/AreaPath,'{areapath}') "
&"&$select=WorkItemId,Title,WorkItemType,State,Priority,Severity,TagNames,AreaSK "
&"&$expand=AssignedTo($select=UserName),Iteration($select=IterationPath),Area($select=AreaPath), "
&"Links( "
&"$filter=LinkTypeName eq 'Related' "
&"and TargetWorkItem/WorkItemType eq 'User Story'; "
&"$select=LinkTypeName; "
&"$expand=TargetWorkItem($select=WorkItemType,WorkItemId,Title,State) "
&") "
,null, [Implementation="2.0",OmitValues = ODataOmitValues.Nulls,ODataVersion = 4])
in
Source
Convert your list into table and add new column where you use your created function, something like:
let
Source = Table.FromList(YourListOfProjects)
,InvokedFunction = Table.AddColumn(Source, "GetDataForProject", each GetDataForProject([Column1]))
in
InvokedFunction
You can then expand tables in new created column:
In result you get appended tables.

Export data from SQL database to CSV file, some rows of data get split into more than one row

When I export data from my SQL database to CSV file, some rows of data (records) get split into more than one row, as if there is a CR. I know that one reason is the following: One of the columns of the data is "Notes" that contains text that sometimes does contain a CR; I understand why this causes a new row in the CSV, but I would like that not to happen, either. How can I strip the CR, but add a period+space to format the Note so it's readable even without the CR?
However, I also get the extra row even if there is no CR, meaning the CSV has a blank row after a record, or the Note is on an extra line. I've included a screenshot of a portion of the CSV file to illustrate this and also illustrate that not all records show the behavior.
Here is my code. I did not write this, I inherited it. Also, I am not very experienced writing code.
header('Content-Type: application/msexcel-tab');
header('Content-Disposition: attachment; filename="Invaders of Texas Data -- '.date("Y-m-d").'.xls"');
$whereclause = '';
$passclause = '';
$satellite = $_REQUEST['satellite'];
$collector = $_REQUEST['collector'];
$sn = $_REQUEST['sn'];
$cn = $_REQUEST['cn'];
if ($satellite){
$whereclause .= " AND `satellite_id` = ".$satellite." ";
$passclause .= "&satellite=".$satellite;
}
if ($collector){
$whereclause .= " AND `collector_id` = ".$collector." ";
$passclause .= "&collector=".$collector;
}
if ($sn){
$whereclause .= " AND `plant_id` LIKE '".$sn."' ";
$passclause .= "&sn=".$sn;
}
if ($cn){
$whereclause .= " AND `plant_id` LIKE '".$cn."' ";
$passclause .= "&cn=".$cn;
}
$count_sql = "
SELECT COUNT(*) AS `counttotal`
FROM `inv_sites`
WHERE 1
$whereclause
AND `valid` LIKE 'Yes'
;
";
//echo $count_sql;
$count_total = mysql_fetch_array(mysql_query($count_sql));
$sql = "
SELECT *
FROM `inv_sites`
WHERE 1
$whereclause
AND `valid` LIKE 'Yes'
ORDER BY `collection_date` ASC
;
";
$the_result = mysql_query($sql);
?>
Invaders of Texas
www.texasinvasives.org
Exported: <?= date("Y-m-d G:i"); ?>
Obs_ID Date USDA Species Time_Spent Satellite Collector Lat Long Location_Error Loc_Err_Units Disturbance Patch_Type Abundance Validated Valid_Name Valid_Date Notes
<?php
if ($this_row = mysql_fetch_array($the_result)){
do {
?>
<?=$this_row['site_id'];?> <?=$this_row['collection_date'];?> <?=$this_row['plant_id']?> <?=sn_from_usda($this_row['plant_id'])?> <?=$this_row['collection_time'];?> <?=satellite_from_id($this_row['satellite_id']);?> <?=$this_row['collector_id'];?> <?=$this_row['latitude'];?> <?=$this_row['longitude'];?> <?=$this_row['error'];?> <?=$this_row['error_unit'];?> <?=$this_row['disturbance'];?> <?=$this_row['patch_type'];?> <?=$this_row['abundance'];?> <?=$this_row['valid'];?> <?=$this_row['valid_name'];?> <?=$this_row['valid_date'];?> <?=$this_row['notes'];?>
<?php
} while ($this_row = mysql_fetch_array($the_result));
}
?>
I'd appreciate any help!! Thanks.
You could replace the newlines in the PHP or the SQL query.
You have the following line above.
<?=$this_row['site_id'];?> <?=$this_row['collection_date'];?> <?=$this_row['plant_id']?> <?=sn_from_usda($this_row['plant_id'])?> <?=$this_row['collection_time'];?> <?=satellite_from_id($this_row['satellite_id']);?> <?=$this_row['collector_id'];?> <?=$this_row['latitude'];?> <?=$this_row['longitude'];?> <?=$this_row['error'];?> <?=$this_row['error_unit'];?> <?=$this_row['disturbance'];?> <?=$this_row['patch_type'];?> <?=$this_row['abundance'];?> <?=$this_row['valid'];?> <?=$this_row['valid_name'];?> <?=$this_row['valid_date'];?> <?=$this_row['notes'];?>
Try replacing it with the below (the change is on the very end).
<?=$this_row['site_id'];?> <?=$this_row['collection_date'];?> <?=$this_row['plant_id']?> <?=sn_from_usda($this_row['plant_id'])?> <?=$this_row['collection_time'];?> <?=satellite_from_id($this_row['satellite_id']);?> <?=$this_row['collector_id'];?> <?=$this_row['latitude'];?> <?=$this_row['longitude'];?> <?=$this_row['error'];?> <?=$this_row['error_unit'];?> <?=$this_row['disturbance'];?> <?=$this_row['patch_type'];?> <?=$this_row['abundance'];?> <?=$this_row['valid'];?> <?=$this_row['valid_name'];?> <?=$this_row['valid_date'];?> <?=trim(preg_replace('/\s+/', ' ', $this_row['notes']));?>
The preg_replace allows you to use regular expressions in php to remove the newlines.
If this doesn't work you may need to alter your SQL query to remove the newline from the database query.
See this post
Pete

Date function in access vba outputting time

I am trying to update a date field in a table to the current date when a button is clicked on a form and that given field is empty. However, when the field is updated, the output is the time 12:00:05, not a date at all. When year(date) is used instead, 7/7/1905 is the output. I am not sure why these values are my outputs. Here is my code:
Dim ctl As Control
Set ctl = [Forms]![frm1]![subfrm1].[Form]![CloseDate]
If IsNull(ctl) Then
DoCmd.SetWarnings False
DoCmd.RunSQL "Update tbl1 SET [CloseItem] = ""YES"" WHERE [ID] = " & [Forms]![frm1]![ID].Value & " AND [Item#] = " & [Forms]![frm1]![subfrm1].[Form]![ItemID].Value
DoCmd.RunSQL "Update tbl1 SET [CloseDate] = " & Date & " WHERE [ID] = " & [Forms]![frm1]![ID].Value & " AND [ItemID] = " & [Forms]![frm1]![subfrm1].[Form]![ItemID].Value
' Output is 12:00:05
' OR DoCmd.RunSQL "Update tbl1 SET [CloseDate] = " & Year(Date) & " WHERE [ID] = " & [Forms]![frm1]![ID].Value & " AND [ItemID] = " & [Forms]![frm1]![subfrm1].[Form]![ItemID].Value
DoCmd.RefreshRecord
' Output is 7/7/1905
End If
How can I get it to output the correct date?
Examine the string your code builds for this segment of the UPDATE statement. (This is an example copied from the Access Immediate window. You can go there with Ctrl+g)
? "Update tbl1 SET [CloseDate] = " & Date & " WHERE [ID] = "
Update tbl1 SET [CloseDate] = 2/16/2015 WHERE [ID] =
The db engine does not see 2/16/2015 as a Date/Time value. Instead, it treats that as 2 divided by 16 divided by 2015. And the resulting number, when expressed as a Date/Time value, gives you this ...
? Format(2/16/2015, "yyyy-m-d hh:nn:ss")
1899-12-30 00:00:05
You can signal the db engine that 2/16/2015 is a Date/Time value by enclosing it in # delimiters like this: #2/16/2015#
However, since the db engine understands the Date() function, you can use that function name directly in your UPDATE statement and not bother about concatenating in a value with proper delimiters.
Dim strUpdate As String
strUpdate = "Update tbl1 SET [CloseDate] = Date() WHERE [ID] = " & _
[Forms]![frm1]![ID].Value & " AND [ItemID] = " & _
[Forms]![frm1]![subfrm1].[Form]![ItemID].Value
Debug.Print strUpdate
CurrentDb.Execute strUpdate, dbFailOnError

Select statement should return only one record

I want to fetch and print only one record from database mysql.
#Select backlogs
{
my $backlog_req = "select id, name, startDate, endDate, parent_id " .
" from backlogs " ;
"where backlogtype='Iteration' and id = $iteration" ;
print "ITERATION_ID : " . $iteration . "\n";
my $sth = $dbh->prepare( $backlog_req );
$sth->execute() ;
$sth->bind_columns( undef, \$backlog_id, \$bl_name, \$bl_sd, \$bl_ed, \$prod_id ) ;
while( $sth->fetch() ) {
$Backlogs->{ $backlog_id } = { name => $bl_name, start_date => substr($bl_sd, 0, 10), end_date => substr($bl_ed, 0, 10) } ;
print "$bl_name ($backlog_id): $bl_sd -> $bl_ed\n";
}
this returns all the rows with Iteration as backlogtype. I want only backlogtype as Iteration and Id which i am providing through command line argument. as i specified in where.
Change this:
" from backlogs " ;
to this:
" from backlogs " .
to include the WHERE-clause in your query.
Also, you should add use warnings; to the start of your script. It would have warned you about this (by complaining that your WHERE-clause-only statement was a Useless use of string in void context).

SphinxQL and SPH_MATCH_ANY

I am using SphinxQL to query Sphinxsearch engine. I want to simulate the SPH_MATCH_ANY which is implemented in the php API like this :
$cl->SetMatchMode(SPH_MATCH_ANY);
$cl->Query("test query", "index");
=> search for docs matching with "test" OR "query"
So, I have written a function (php) to replace spaces and other special chars with pipes (|) in order to use it with SphinxQL :
function formatQuery($str) {
return trim(preg_replace('/[^-_\'a-z0-9]+/', '|', $str), ' |');
}
$str = "test query";
$sql = "SELECT * FROM index WHERE MATCH('" . addslashes(formatQuery($str)) . "')";
=> SELECT * FROM index WHERE MATCH('test|query');
The problem is, for some characters like - (minus), it can break the query, example :
$str = "i-phone is great";
$sql = "SELECT * FROM index WHERE MATCH('" . addslashes(formatQuery($str)) . "')";
=> SELECT * FROM index WHERE MATCH('i-phone|is|great')
=> ok
$str = "i - phone is great";
$sql = "SELECT * FROM index WHERE MATCH('" . addslashes(formatQuery($str)) . "')";
=> SELECT * FROM index WHERE MATCH('i|-|phone|is|great')
=> broken query because of "|-|"
Do you know a better way to make SphinxQL queries work in SPH_MATCH_ANY mode? or a better regexp to make it works for all cases?
I know I could use a more restrictive regexp like this:
preg_replace('/[^a-z0-9]+/', '|', $str)
but it would split strings like "i-phone is great" in 'i|phone|is|great' and I don't want that...
Thank you,
Nico
One way might be to use quorom
$sql = "SELECT * FROM index WHERE MATCH('\"" . addslashes($str) . "\"/1')";
you will need to add - to your charset_table tho, so it becomes part of a word.
The other option is
$query = preg_replace('/(\w+?)[-\'](\w+?)/','$1~$2',$query);
$query = preg_replace('/[^\w\~]+/','|',$query);
$query = preg_replace('/(\w+~\w[\w~]*)/e','"\"".str_replace("~"," ","$1")."\""',$query);
To turn it into a phrase.