HOW TO GET QUERY IN SQL USING PHP IN SQL TIGGERING - php

This is my code my $sql variable didn't give query plese help me for this I try this but I couldn't please help me with that
<?php
$connect = mysqli_connect("localhost", "root", "", "finger");
$f= "";
$l= "";
$sql = "CREATE TRIGGER `ersdmmmmecv` AFTER INSERT ON `event` FOR EACH ROW SELECT fname,Lname INTO $f,$l FROM user WHERE id=NEW.id;"
$result = mysqli_query($connect, $sql);
?>

You cannot use a MySQL trigger to update PHP variables. If you want the values of $f and $l to update whenever a new record is inserted into your event table, you need to do this in PHP entirely.
Something along these lines should work (note: I did not test this myself):
$f = "";
$l = "";
$new_id = "id_value";
$insert = $connect->prepare("INSERT INTO `event` (`id`, `column2`, `column3`) VALUES (?, ?, ?)");
$insert->bind_param("sss", $new_id, "value2", "value3");
if ($insert->execute() === FALSE) {
echo 'Could not insert event: ' . $insert->error;
} else {
// If `event`.`id` is actually an AUTO_INCREMENT column, and you don't
// specify it in your INSERT query, use this here:
// $new_id = $insert->insert_id;
$select = $connect->prepare("SELECT `fname`, `Lname` FROM `user` WHERE `id` = ?");
$select->bind_param("s", $new_id);
$select->execute();
$select->bind_result($f, $l);
$success = $select->fetch();
if ($success !== TRUE) {
echo 'Could not update $f and $l with new values: '
. ($select->error ?: 'No user with id: ' . $new_id);
}
}
If you have multiple places in your code where you insert data into the events table, I would personally wrap this in a function so I wouldn't have to repeat this every time.

This is the Trigger Solution
<?php
$connect = mysqli_connect("localhost", "root", "", "finger");
$sql1 = "CREATE TRIGGER `ersdmmmmecv` AFTER INSERT ON `event` FOR EACH ROW INSERT INTO res (fres,lres) VALUES SELECT fname,Lname FROM user WHERE id=NEW.id;";
$result2 = mysqli_query($connect, $sql1);
$sql = "SELECT * FROM res;";
if( !( $selectRes = mysqli_query($connect, $sql) ) ){
echo 'Retrieval of data from Database Failed - #';
}else{
?>
<table border="2">
<thead>
<tr>
<th>fName</th>
<th>lname</th>
</tr>
</thead>
<tbody>
<?php
if( mysqli_num_rows( $selectRes )==0 ){
$print_output= '<tr><td colspan="4">No Rows Returned</td></tr>';
}else{
while( $row = mysqli_fetch_assoc( $selectRes ) ){
$print_output="<tr><td>{$row['fres']}</td><td>{$row['lres']}</td></tr>\n";
}
}
?>
</tbody>
</table>
<?php
try
{
$fp=pfsockopen("127.0.0.1", 80);
fputs($fp, $print_output);
fclose($fp);
echo 'Successfully Printed '.$print_output;
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
<?php
}
?>
<?php
$sql2= "DROP TRIGGER ersdmmmmecv";
$result1 = mysqli_query($connect, $sql2);
$sql3= "DELETE FROM res;";
$result3 = mysqli_query($connect, $sql3);
?>
<script>
setTimeout(function () { window.location.reload(); }, 1*60*1000);
// just show current time stamp to see time of last refresh.
document.write(new Date());
</script>

Related

Inserting data into sql it inserts two into rows, and i dont know why

When Inserting data into SQL it inserts two into rows, and I don't know why.
most probably of the if statement I added after the results you can find it as my comment:
// id_no update
And I used the select query two times to fetch the id and make it an auto-increment thing.
my table:
<?PHP
$query = "SELECT id_no FROM db_name ORDER BY id_no DESC";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
$lastid = $row['id_no'];
if(empty($lastid))
{
$number = "SX000001";
}
else
{
$idd = str_replace("SX", "", $lastid);
$id = str_pad($idd + 1, 6, 0, STR_PAD_LEFT);
$number = 'SX'.$id;
}
?>
<?PHP
if(isset($_POST['add_id']))
{
$id_no = mysqli_real_escape_string($con,$_POST['id_no']);
$sql="INSERT INTO `db_name`(`id_no`) VALUES ('$id_no')";
$result=mysqli_query($con,$sql);
// id_no update
if(mysqli_query($con,$sql))
{
$query = "SELECT id_no FROM db_name ORDER BY id_no DESC";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
$lastid = $row['id_no'];
if(empty($lastid))
{
$number = "SX000001";
}
else
{
$idd = str_replace("SX", "", $lastid);
$id = str_pad($idd + 1, 6, 0, STR_PAD_LEFT);
$number = 'SX'.$id;
}
}
else
{
echo "Record Faileddd";
}
if($result)
{
$success="Post has been added successfully";
} else
{
$error="Something went wrong!";
}
$id_no = '';
}
?>
You should check if $resultĀ is truthy to see if the insertion succeded (without running another query):
$id_no = mysqli_real_escape_string($con,$_POST['id_no']);
$sql="INSERT INTO `db_name`(`id_no`) VALUES ('$id_no')";
$result=mysqli_query($con,$sql);
// id_no update
if($result)
{
...
}

Using transactions in PHP and MySQL

I'm a learner of PHP. This commit and rollback process does the task at each line. How can I commit and rollback all at once?
<?php
$con = mysql_connect('localhost','user', 'abcdefg');
if(!con)
{
echo "Can't connect to db.";
}else {
mysql_select_db('test');
}
if(!file_exits('test.csv')
{
echo "Can't find the file.";
}
$ar_1 = file('test.csv', FILE_IGNORE_NEW_LINES);
foreach ($ar_1 as $ar1)
{
$test = explode(",", $ar1);
$sql = "SELECT * FROM DB WHERE CD = '$test[0]'";
$result = mysql_query_($sql);
$sql = "INSERT INTO DB(CODE) VALUES ('$test[0]');";
$result = mysql_query($sql);
if($result === true)
{
//Commit
$sql = "commit";
mysql_query($sql);
echo "Committed";
}else {
//Rollback
$sql = "rollback";
mysql_query($sql);
echo "Rollback";
}
}
mysql_close($con);
?>
you need to commit out of the loop, i used $bool to see if there somewhere the $result isn't true
it will look something like :
edit:
breaking from the loop when something is wrong as you don't need to continue looping to other elements.
$bool = 1;
foreach ($ar_1 as $ar1)
{
$test = explode(",", $ar1);
$sql = "SELECT * FROM DB WHERE CD = '$test[0]'";
$result = mysql_query_($sql);
$sql = "INSERT INTO DB(CODE) VALUES ('$test[0]');";
$result = mysql_query($sql);
if($result === false)
{
//Rollback
$bool = 0;
$sql = "rollback";
mysql_query($sql);
echo "Rollback";
break;
}
}
if($bool == 1)
{
//Commit
$sql = "commit";
mysql_query($sql);
echo "Committed";
}
mysql_close($con);

Not saving in database table

I want edit record in db table but it doesn't save in db table and nothing changed after i submit this form.
Here codes that i forgot to put.
<?php
require('db.php');
include("auth.php"); //include auth.php file on all secure pages
$id_doc=$_REQUEST['id_doc'];
$query = "SELECT * from doc where id_doc='".$id_doc."'";
$result = mysqli_query($connection, $query) or die ( mysqli_error());
$row = mysqli_fetch_assoc($result);
?>
This is my php codes
<?php
if(isset($_POST['new']) && $_POST['new']==1)
{
$id_doc=$_REQUEST['id_doc'];
$query = "SELECT * from doc where id_doc='".$id_doc."'";
$result = mysqli_query($connection, $query) or die ( mysqli_error());
$row = mysqli_fetch_assoc($result);
$title =$_REQUEST['title'];
$date = $_REQUEST['date'];
$from_to = $_REQUEST['from_to'];
$details = $_REQUEST['details'];
$d_location = $_REQUEST['d_location'];
$d_stat = $_REQUEST['d_stat'];
$update="update doc set title='".$title."', date='".$date."', from_to='".$from_to."', details='".$details."', d_location='".$d_location."', d_stat='".$d_stat."' where id_doc='".$id_doc."'";
mysqli_query($connection, $update) or die(mysql_error());
$status = "File Record Updated Successfully. </br></br><a href='v_doc.php'>View Updated Record</a>";
echo '<p style="color:#FF0000;">'.$status.'</p>';
}else {
// here some else code
}
?>
Not an answer. Too long for a comment.
The issue of parametrised queries aside, I find this easier to read:
UPDATE doc
SET title = '$title'
, date = '$date'
, from_to = '$from_to'
, details = '$details'
, d_location = '$d_location'
, d_stat = '$d_stat'
WHERE id_doc = '$id_doc'
And now see about parametrised queries
Try below:
<?php
if(isset($_POST['new']) && $_POST['new']==1)
{
$id_doc=$_REQUEST['id_doc'];
$query = "SELECT * from doc where id_doc='".$id_doc."'";
$result = mysqli_query($connection, $query) or die ( mysqli_error());
$row = mysqli_fetch_assoc($result);
$title =$_REQUEST['title'];
$date = $_REQUEST['date'];
$from_to = $_REQUEST['from_to'];
$details = $_REQUEST['details'];
$d_location = $_REQUEST['d_location'];
$d_stat = $_REQUEST['d_stat'];
$update="update doc set title='".$title."', date='".$date."', from_to='".$from_to."', details='".$details."', d_location='".$d_location."', d_stat='".$d_stat."' where id_doc='".$id_doc."'";
if(mysqli_query($connection, $update)) {
$status = "File Record Updated Successfully. </br></br><a href='v_doc.php'>View Updated Record</a>";
} else {
die(mysqli_error($connection));
}
echo '<p style="color:#FF0000;">'.$status.'</p>';
} else {
// here some else code
}
?>
This should show you exact error, once you get it. show it here, so we can check and do correction.

How to make cart not duplicate items?

I need to know How to not make item duplicate and add quantity from showitem.php to quantity
but I made update to table in sql but nothing happen to the table I don't know why ?
This is addtocart.php
<?php
session_start();
function addtocart($id,$qty){
if (isset($id)){
//connect to database
$mysqli = mysqli_connect("localhost", "root", "", "e-com");
//create safe values for use
$safe_sel_item_id = mysqli_real_escape_string($mysqli,
$id);
$safe_sel_item_qty = mysqli_real_escape_string($mysqli,$qty);
//validate item and get title and price
$get_iteminfo_sql = "SELECT itemname FROM items WHERE itemid = '".$safe_sel_item_id."'";
$get_iteminfo_res = mysqli_query($mysqli, $get_iteminfo_sql)
or die(mysqli_error($mysqli));
if (mysqli_num_rows($get_iteminfo_res) < 1) {
//free result
mysqli_free_result($get_iteminfo_res);
//close connection to MySQL
mysqli_close($mysqli);
//invalid id, send away
header("Location: seestore.php");
exit;
} else {
//get info
while ($item_info = mysqli_fetch_array($get_iteminfo_res)) {
$item_title = stripslashes($item_info['itemname']);
}
//free result
mysqli_free_result($get_iteminfo_res);
$sql = "select sel_item_qty from shooppertrack where sel_item_id = '" .
$safe_sel_item_id . "'";
$res = mysqli_query($mysqli, $sql);
while ($res_info = mysqli_fetch_array($get_iteminfo_res)){
$update_qty = $res['sel_item_qty'];
}
// does quantity exist?
if (mysqli_num_rows($res) > 0 ) {
// get sel_item_qty, add 1, run update query
"UPDATE shooppertrack SET sel_item_qty = sel_item_qty + $update_qty
WHERE sel_item_id = '" .$safe_sel_item_id . "'" ;
} else {
//add info to cart table
$addtocart_sql = "INSERT INTO shooppertrack
(session_id, sel_item_id, sel_item_qty,
date_added)
VALUES ('".$_COOKIE['PHPSESSID']."',
'".$safe_sel_item_id."',
'".$safe_sel_item_qty."',
now())";
$addtocart_res = mysqli_query($mysqli, $addtocart_sql)
or die(mysqli_error($mysqli));
}
//close connection to MySQL
mysqli_close($mysqli);
//redirect to showcart page
header("Location: showcart.php");
exit;
}
} else {
//send them somewhere else
header("Location: seestore.php");
exit;
}
}
addtocart($_POST['sel_item_id'],$_POST['sel_item_qty']);
?>
This is showitem.php
<?php
function show($x){
//connect to database
$mysqli = mysqli_connect("localhost", "root", "", "e-com");
$display_block = "<h1>My Store - Item Detail</h1>";
//create safe values for use
$safe_item_id = mysqli_real_escape_string($mysqli, $x);
//validate item
$get_item_sql = "SELECT c.cat_id , c.cat_name, si.itemid, si.itemname,
si.price, si.descripition, si.photo FROM items
AS si LEFT JOIN categories AS c on c.cat_id = si.cat_id
WHERE si.itemid = '".$safe_item_id."'";
$get_item_res = mysqli_query($mysqli, $get_item_sql)
or die(mysqli_error($mysqli));
if (mysqli_num_rows($get_item_res) < 1) {
//invalid item
$display_block .= "<p><em>Invalid item selection.</em></p>";
} else {
//valid item, get info
while ($item_info = mysqli_fetch_array($get_item_res)) {
$cat_id = $item_info['cat_id'];
$cat_title = strtoupper(stripslashes($item_info['cat_name']));
$item_title = stripslashes($item_info['itemname']);
$item_price = $item_info['price'];
$item_desc = stripslashes($item_info['descripition']);
$item_image = $item_info['photo'];
}
//make breadcrumb trail & display of item
$display_block .= <<<END_OF_TEXT
<p><em>You are viewing:</em><br/>
<strong>$cat_title > $item_title</strong></p>
<div style="float: left;"><img src="$item_image" alt="$item_title" /></div>
<div style="float: left; padding-left: 12px">
<p><strong>Description:</strong><br/>$item_desc</p>
<p><strong>Price:</strong> \$$item_price</p>
<form method="POST" action="addtocart.php">
END_OF_TEXT;
//free result
mysqli_free_result($get_item_res);
$display_block .= "
<p><label for=\"sel_item_qty\">Select Quantity:</label>
<select id=\"sel_item_qty\" name=\"sel_item_qty\">";
for($i=1; $i<11; $i++) {
$display_block .= "<option value=\"".$i."\">".$i."</option>";
}
$display_block .=<<<ENDOFTEXT
</select><p>
<input type="hidden" name="sel_item_id" value="$_GET[itemid]" />
<button type="submit" name="submit" value="submit">Add to Cart</button>
</form>
</div>
ENDOFTEXT;
}
return $display_block;
//close connection to MySQL
mysqli_close($mysqli);
}
?>
You need to query your cart for that item and session before inserting. If it exists, you should update the quantity instead.
$sql = 'select sel_item_qty from shooppertrack where sel_item_id = ' .
$safe_sel_item_id . ' and session_id = ' $_COOKIE['PHPSESSID'];
$res = mysqli_query($mysqli, $sql);
// does quantity exist?
if (mysqli_num_rows($res) > 0 ) {
// get sel_item_qty, add 1, run update query
} else {
// run your insert query
}
Try this
//add info to cart table
$sql = "Select session_id, sel_item_id from shooppertrack where session_id = $sid and sel_item_id = $si_id";
$res = mysqli_query($mysqli, $sql);
if(mysqli_num_rows($res) == 1)
{
// update with qty +1;
}else{
$addtocart_sql = "INSERT INTO shooppertrack
(session_id, sel_item_id, sel_item_qty,
date_added)
VALUES ('".$_COOKIE['PHPSESSID']."',
'".$safe_sel_item_id."',
'".$safe_sel_item_qty."',
now())";
$addtocart_res = mysqli_query($mysqli, $addtocart_sql)
or die(mysqli_error($mysqli));
}

mysql_multi_query inside a foreach loop

I try to parse a xml file and store each node to a mysql db. The problem is that it store the data in the first loop and returns error in the second time. If I refresh the page it stores the rest data as well.
I try to understand why does it behave in a such way
<?php
try{
$records = simplexml_load_file("file.xml");
} catch (Exception $e){
echo "xml problem";
}
#replace loclhost,user, pass, dbname
$db = mysqli_connect("localhost", "root", "", "project") or die("could not connect:" . mysqli_connect_error());
foreach($records->record as $rec){
$species_location_x = $rec->species_lang;
$species_location_y = $rec->species_long;
$species_abundance = (string)$rec->abundance;
$species_text = (string)$rec->text;
$species_scene_photo = (string)$rec->space_photo;
$species_photo_loc = (string)$rec->specimen_photo;
$site_name = (string)$rec->site->sitename;
$site_location = (string)$rec->site->sitelocation;
$site_description = (string)$rec->site->sitedescription;
$user_name = (string)$rec->user->lastname;
$user_phone = (string)$rec->user->namephone;
$user_email = (string)$rec->user->useremail;
$species_name = (string)$rec->species->species_name;
#print_r($species_location_x." ".$species_location_y." ".$species_abundance." ".$species_text." ".$species_scene_photo." ".$species_photo_loc);
#print_r($site_name." ".$site_location." ".$site_description);
#print_r($user_name." ".$user_phone." ".$user_email);
#print_r($species_name);
$multiq = "INSERT INTO users (user_name, user_phone, user_email)
VALUES ('$user_name', '$user_phone', '$user_email');" ;
$multiq .= "INSERT INTO records (user_name, record_location, record_abundance, record_text, record_scene_photo_location, record_specimen_photo_location )
VALUES ( '$user_name',
GeomFromText('point($species_location_x $species_location_y)'),
'$species_abundance',
'$species_text',
'$species_scene_photo',
'$species_photo_loc');" ;
$multiq .= "INSERT INTO species (species_name, records_id )
VALUES ( '$species_name', (select record_id from records where user_name = '$user_name' and record_abundance = '$species_abundance' and record_text = '$species_text'));" ;
$multiq .= "INSERT INTO sites (site_name, site_location, site_description, species_id)
VALUES ('$site_name', '$site_location', '$site_description', (select species_id from species where species_name='$species_name'));";
if(mysqli_multi_query($db, $multiq)){
echo "records added successfully\n";
}
else{
echo "problem";
}
}
mysqli_close($db);

Categories