Deleting row from table in mysql database - mysql

I am trying to delete a certain item from a database depending on conditions. Here is what I have:
while ($row = mysql_fetch_array($result)) {
$now = strtotime("now");
$dateArray = date_parse_from_format("n-j-Y", $row["date"]);
$event_date = strtotime($dateArray['year'].'-'.$dateArray['month'].'-'.$dateArray['day']);
// temp user array
$event = array();
if($event_date > $now) {
//Event is in the future
$pid_check =$row["pid"];
$event["pid"] = $row["pid"];
$event["name"] = $row["name"];
$event["longitude"] = $row["longitude"];
$event["latitude"] = $row["latitude"];
$event["pavement"] = $row["pavement"];
$event["traffic"] = $row["traffic"];
$event["environment"] = $row["environment"];
$event["image_b64"] = $row["image_b64"];
$event["date"] = $row["date"];
$event["time"] = $row["time"];
$event["type"] = $row["type"];
// push single product into final response array
array_push($response["events"], $event);
} else {
$result2 = mysql_query("DELETE FROM events WHERE pid = $pid_check");
}
}
But when I try this it comes up blank, when I comment out result2 it works but doesn't delete(duh). How can I get it to delete? Sorry if this is a simple question, my knowledge of the language is not much.

I think $pid_check is getting set only if the condition in your if is TRUE.
It's not getting set for the else branch.
One option is to relocate the assignment of $pid_check before the if test.

Related

How to insert multiple row with different ID in Laravel

I need a way to insert multiple rows into sql table, and return all inserted different primary key ids with one sql query.
foreach($request->size as $key => $value)
{
$size = new sizes;
$size->size_name = $request->size[$key];
$size->size_price = $request->sizeprice[$key];
$size->pid = $last_id;
$size->save();
$size_last_id = $size->id;
}
foreach($request->stock as $key => $value)
{
$stock = new stocks;
$stock->pid = $last_id;
$stock->size_id = $size_last_id;
$stock->stock_qty = $request->stock[$key];
$stock->save();
}
Please find the attached this image.
https://i.stack.imgur.com/LsJHZ.png
$size_last_id = $size->id;
Above code will return only last inserted row's id as you are inserting data using foreach loop.
Better to store all the ids in an array, declare a variable as an array and push id to array.
Sample code.
$size_last_id = [];
foreach($request->size as $key => $value)
{
$size = new sizes;
$size->size_name = $request->size[$key];
$size->size_price = $request->sizeprice[$key];
$size->pid = $last_id;
$size->save();
array_push($size_last_id, $size->id);
}
This will store all the inserted ids to array.
Read More about array_push
Hope this will be useful.

Creating Json file from mysql

i can't get more than one return in this json. when the original query returns 90k results.
i can't figure out what's hapening.
also the return i get isn't organized as it should. it return the following
{"material":["R8190300000","0"],"grid":["R8190300000","0"]}
sorry to ask this i have been looking for an answer but couln't get it in the internet.
<?php
$link = mysqli_connect("localhost","blablabla","blablabla","blablabla");
if (mysqli_connect_error()) {
die("Could not connect to database");
}
$query =" SELECT material,grid FROM ZATPN";
if( $result = mysqli_query( $link, $query)){
while ($row = mysqli_fetch_row($result)) {
$resultado['material']=$row;
$resultado['grid']=$row;
}
} else {
echo"doesnt work";
}
file_put_contents("data.json", json_encode($resultado));
?>
The problem is that you are overriding the value for the array keys:
$resultado['material']=$row;
$resultado['grid']=$row;
At the end you will have only the last 2 rows; I suggest you to use something like:
$resultado['material'][] = $row;
$resultado['grid'][] = $row;
This will save you pair rows in $resultado['grid'] and unpaired rows in $resultado['material'];
After the information in comments you can use this code:
$allResults = array();
while ($object = mysqli_fetch_object($result)) {
$resultado['id'] = $object->id;
$resultado['name'] = $object->name;
$resultado['item'] = $object->item;
$resultado['price'] = $object->price;
$allResults[] = $resultado;
}
file_put_contents("data.json", json_encode($allResults));

Pagination in smarty

I want to add pagination in my site when user search for some item. I have tried the following code:
//Array Declaration//
$pages = array();
$userlist = array();
//paging variable//
$userlist_pg = $_GET['list_pg'];
if(empty($userlist_pg))
$userlist_pg = 1;
else
$userlist_pg=$_GET['list_pg'];
$userlist_limit = 10;//ADMIN_ITEMLIST_PER_PAGE;
$userlist_start = (($userlist_pg - 1) * $userlist_limit );
$userlist_currentpage = $userlist_pg;
$userlist_back = $userlist_pg-1;
$userlist_next = $userlist_pg + 1;
$query_string = "select cms_id,cms_variable,cms_page_name,cms_last_edited from tbl_cms";
//Paging variables start from here-------------------------
$orderlist = array();
$paging = new PagedResults();
$paging->TotalResults = table_query_count($query_string);
$InfoArray = $paging->InfoArray();
$query_string.=" LIMIT ".$InfoArray["MYSQL_LIMIT1"].", ".$InfoArray["MYSQL_LIMIT2"];
$PageVarName = 'client_page';
$smarty->assign("page_display", getpagelist($InfoArray["CURRENT_PAGE"],$InfoArray["PREV_PAGE"],$InfoArray["NEXT_PAGE"],$InfoArray["TOTAL_PAGES"],$InfoArray["Second_next"],$InfoArray["third_next"],$InfoArray["fourth_next"],$PageVarName));
$smarty->assign("currentpage",$InfoArray["CURRENT_PAGE"]);
$smarty->assign("total_pages",$InfoArray["TOTAL_PAGES"]);
//Paging variables end here-------------------------
it gives the following errors.
Call to undefined function table_query_count() in /home/www/jobplacement4u.com/hungry_uni/modules/search/action/search_action.php on line 110
Class 'PagedResults' not found in /home/www/jobplacement4u.com/hungry_uni/modules/search/action/search_action.php on line 30
Call to undefined method PagedResults::InfoArray() in /home/www/jobplacement4u.com/hungry_uni/modules/search/action/search_action.php on line 111
Looks like you forgot to include the file(s) with definition of function table_query_count and class PagedResults

Was: Grab the last inserted id - mysql Now: Where should we call the last insert id?

Here's the thing, I don't have access to code that inserts data into a given table. However, I need to add related additional data into another table. So, I was thinking about grabbing the last inserted ID and from there... insert the related data into that other table.
Since I don't have access to the statement, I believe that mysql last insert id function will be of no use here.
All the PDO::lastInsertId examples that I see, are also attached to some "insert query" before it, so no use as well.
How can I grab the last inserted ID on the cases were we DON'T have access to the original insert statement ?
Data flow:
It starts here: signup.tpl
Where we have:
onclick="checkoutvalidate();return false"
On the js we have:
function checkoutvalidate() {
$.post("order/index.php", 'a=validatecheckout&'+$("#orderfrm").serialize(),
function(data){
if (data) {
...
} else {
document.orderfrm.submit();
}
});
So, now, let's look for "validatecheckout" into index.php
And we found it:
We can't read along this lines, anything concerning the insertion. The immediately after that I can get is, after the conditional statement - right ?
if ($a=="validatecheckout") {
$errormessage = '';
$productinfo = getProductInfo($pid);
if ($productinfo['type']=='server') {
if (!$hostname) $errormessage .= "<li>".$_LANG['ordererrorservernohostname'];
else {
$result = select_query("tblhosting","COUNT(*)",array("domain"=>$hostname.'.'.$domain,"domainstatus"=>array("sqltype"=>"NEQ","value"=>"Cancelled"),"domainstatus"=>array("sqltype"=>"NEQ","value"=>"Terminated"),"domainstatus"=>array("sqltype"=>"NEQ","value"=>"Fraud")));
$data = mysql_fetch_array($result);
$existingcount = $data[0];
if ($existingcount) $errormessage .= "<li>".$_LANG['ordererrorserverhostnameinuse'];
}
if ((!$ns1prefix)OR(!$ns2prefix)) $errormessage .= "<li>".$_LANG['ordererrorservernonameservers'];
if (!$rootpw) $errormessage .= "<li>".$_LANG['ordererrorservernorootpw'];
}
if (is_array($configoption)) {
foreach ($configoption AS $opid=>$opid2) {
$result = select_query("tblproductconfigoptions","",array("id"=>$opid));
$data = mysql_fetch_array($result);
$optionname = $data["optionname"];
$optiontype = $data["optiontype"];
$qtyminimum = $data["qtyminimum"];
$qtymaximum = $data["qtymaximum"];
if ($optiontype==4) {
$opid2 = (int)$opid2;
if ($opid2<0) $opid2=0;
if ((($qtyminimum)OR($qtymaximum))AND(($opid2<$qtyminimum)OR($opid2>$qtymaximum))) {
$errormessage .= "<li>".sprintf($_LANG['configoptionqtyminmax'],$optionname,$qtyminimum,$qtymaximum);
$opid2=0;
}
}
}
}
$errormessage .= checkCustomFields($customfield);
if (!$_SESSION['uid']) {
if ($_REQUEST['signuptype']=="new") {
$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
$companyname = $_REQUEST['companyname'];
$email = $_REQUEST['email'];
$address1 = $_REQUEST['address1'];
$address2 = $_REQUEST['address2'];
$city = $_REQUEST['city'];
$state = $_REQUEST['state'];
$postcode = $_REQUEST['postcode'];
$country = $_REQUEST['country'];
$phonenumber = $_REQUEST['phonenumber'];
$password1 = $_REQUEST['password1'];
$password2 = $_REQUEST['password2'];
$temperrormsg = $errormessage;
$errormessage = $temperrormsg.checkDetailsareValid($firstname,$lastname,$email,$address1,$city,$state,$postcode,$phonenumber,$password1,$password2);
$errormessage .= checkPasswordStrength($password1);
} else {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (!validateClientLogin($username,$password)) $errormessage .= "<li>".$_LANG['loginincorrect'];
}
}
if (($CONFIG['EnableTOSAccept'])AND(!$_REQUEST['accepttos'])) $errormessage .= "<li>".$_LANG['ordererrortermsofservice'];
$_SESSION['cart']['paymentmethod'] = $_REQUEST['paymentmethod'];
if ($errormessage) echo $_LANG['ordererrorsoccurred']."<br /><ul>".$errormessage."</ul>";
else {
if ($_REQUEST['signuptype']=="new") {
$userid = addClient($firstname,$lastname,$companyname,$email,$address1,$address2,$city,$state,$postcode,$country,$phonenumber,$password1);
}
}
//DO THE DO INSERT_LAST_ID() here ?
}
Thanks in advance,
MEM
After the insert statement you can fire another query:
SELECT LAST_INSERT_ID();
and this will return one row with one column containing the id.
Docs: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
mysql> SELECT LAST_INSERT_ID();
-> 195
This works per connection so there is no problem if another thread writes into the table. But your SELECT needs to be executed 'RIGHT AFTER'/'As the next query' after the insert query ran
Edit
An example:
$dbConnection = MyMagic::getMeTheDatabase("please");
$oSomeFunkyCode->createThatOneRowInTheDatabase($dbConnection);
$result = $dbConnection->query("SELECT LAST_INSERT_ID();");
// ... fetch that one value and you are good to go
If the column is a simple auto_incrementing integer, you could use SELECT MAX(MyAutoincrementingColumn) FROM MyTable. You might risk selecting a row that has been inserted by another user in the meantime, if your users are not using transactions.
If you don't have access to the last INSERT line, you can make a subquery to find the last inserted id:
select max(id) from <table>

Linq-2-Sql code: Does this scale?

I'm just starting to use linq to sql. I'm hoping that someone can verify that linq-2-sql has deferred execution until the foreach loop is executed. Over all, can someone tell me if this code scales. It's a simple get method with a few search parameters. Thanks!
Code:
public static IList<Content> GetContent(int contentTypeID, int feedID, DateTime? date, string text)
{
List<Content> contentList = new List<Content>();
using (DataContext db = new DataContext())
{
var contentTypes = db.ytv_ContentTypes.Where(p => contentTypeID == -1 || p.ContentTypeID == contentTypeID);
var feeds = db.ytv_Feeds.Where(p => p.FeedID == -1 || p.FeedID == feedID);
var targetFeeds = from f in feeds
join c in contentTypes on f.ContentTypeID equals c.ContentTypeID
select new { FeedID = f.FeedID, ContentType = f.ContentTypeID };
var content = from t in targetFeeds
join c in db.ytv_Contents on t.FeedID equals c.FeedID
select new { Content = c, ContentTypeID = t.ContentType };
if (String.IsNullOrEmpty(text))
{
content = content.Where(p => p.Content.Name.Contains(text) || p.Content.Description.Contains(text));
}
if (date != null)
{
DateTime dateTemp = Convert.ToDateTime(date);
content = content.Where(p => p.Content.StartDate <= dateTemp && p.Content.EndDate >= dateTemp);
}
//Execution has been defered to this point, correct?
foreach (var c in content)
{
Content item = new Content()
{
ContentID = c.Content.ContentID,
Name = c.Content.Name,
Description = c.Content.Description,
StartDate = c.Content.StartDate,
EndDate = c.Content.EndDate,
ContentTypeID = c.ContentTypeID,
FeedID = c.Content.FeedID,
PreviewHtml = c.Content.PreviewHTML,
SerializedCustomXMLProperties = c.Content.CustomProperties
};
contentList.Add(item);
}
}
//TODO
return contentList;
}
Depends on what you mean with 'scales'. DB side this code has the potential of causing trouble if you are dealing with large tables; SQL Server's optimizer is really poor at handling the "or" operator in where clause predicates and tend to fall back to table scans if there are multiple of them. I'd go for a couple of .Union calls instead to avoid the possibility that SQL falls back to table scans just because of the ||'s.
If you can share more details about the underlying tables and the data in them, it will be easier to give a more detailed answer...