I have made a php script to pull from two different tables within the same database. After the data is pulled, it is put into another table that will hold that specific information for later use. Right now, it will submit the userid and username but will not submit the puid variable I have stated.
Here is the script
include('data.php');
//Database Connection
$con=#mysql_connect("$ip", "$guser", "$gpass")
or die(mysql_error());
//Select Database
$dbcon=#mysql_select_db($forums, $con)
or die(mysql_error());
$search = $_POST['term'];
$sql = mysql_query("select userid, usergroupid, username from $users where username like '%$search%'");
while ($row = mysql_fetch_array($sql)) {
$id = $row['userid'];
$name = $row['username'];
$ugid = $row['usergroupid'];
}
if ($ugid == '21') {
$sql4 = "INSERT INTO $vip (fuid, username) VALUES ('$id', '$name')";
$res2 = #mysql_query($sql4, $con) or die(mysql_error());
$sql2 = mysql_query("SELECT $id, field5 FROM $userfield");
while ($row = mysql_fetch_array($sql2)) {
$puid = $row['field5'];
}
$sql3 = "INSERT INTO $vip (puid) VALUES ('$puid')";
$res = #mysql_query($sql3, $con) or die(mysql_error());
echo 'Completed';
} else {
echo 'User is not VIP';
}
you are not doing those queries for all retrieved rows.you should get those queries inside foreach loop otherwise only the last row will be effected!
Related
I had a previous question on how to do this script and have figured out a way but I am not too sure if I should use this method.
The other post is available here.
Can someone point me in the right direction if there is a more faster/efficient way of running this script as my previous way I was doing it was sometimes taking over an hour to finish.
<?php
//Require admin
require_once("inc/admin.php");
require_once ("../includes/routeros_api.class.php");
//SET
$ip = "10.100.1.1";
//Connect to MikroTik API
$API = new RouterosAPI();
$API->debug = $config['api']['debug'];
if (!$API->connect($ip, $config['api']['username'], $config['api']['password'])) {
echo "Could not connect to RouterOS API";
} else {
$API->write('/ip/accounting/snapshot/take',true);
$READ = $API->read(false);
$ARRAY = $API->parseResponse($READ);
$API->write('/ip/accounting/snapshot/print',true);
$READ = $API->read(false);
$ARRAY = $API->parseResponse($READ);
foreach($ARRAY as $ACCOUNTING) {
$ip_src = $ACCOUNTING['src-address'];
$ip_dst = $ACCOUNTING['dst-address'];
$bytes = $ACCOUNTING['bytes'];
//Check if ip in use UPLOAD
$query = "SELECT id, ipv4 FROM services WHERE ipv4='$ip_src' AND deleted !='1'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array($result);
if(mysqli_num_rows($result) > 0) {
$service_id = $row['id'];
//Update Download Traffic
$check_if_exist_query = "SELECT * FROM traffic_counters WHERE service_id='$service_id' AND date=CURRENT_DATE()";
$check_result = mysqli_query($conn, $check_if_exist_query);
$check_num_rows = mysqli_num_rows($check_result);
if($check_num_rows == 0) {
$add_query = "INSERT INTO traffic_counters (service_id, upload_bytes, date) VALUES ('$service_id', '$bytes', CURRENT_DATE());";
$add_result = mysqli_query($conn, $add_query);
} else {
$update_query = "UPDATE traffic_counters SET
upload_bytes = upload_bytes + $bytes
WHERE service_id='$service_id' AND date=CURRENT_DATE();
";
$update_result = mysqli_query($conn, $update_query);
}
}
//Check if ip in use DOWNLOAD
$query = "SELECT id, ipv4 FROM services WHERE ipv4='$ip_dst' AND deleted !='1'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array($result);
if(mysqli_num_rows($result) > 0) {
$service_id = $row['id'];
//Update Download Traffic
$check_if_exist_query = "SELECT * FROM traffic_counters WHERE service_id='$service_id' AND date=CURRENT_DATE()";
$check_result = mysqli_query($conn, $check_if_exist_query);
$check_num_rows = mysqli_num_rows($check_result);
if($check_num_rows == 0) {
$add_query = "INSERT INTO traffic_counters (service_id, download_bytes, date) VALUES ('$service_id', '$bytes', CURRENT_DATE());";
$add_result = mysqli_query($conn, $add_query);
} else {
$update_query = "UPDATE traffic_counters SET
download_bytes = download_bytes + $bytes
WHERE service_id='$service_id' AND date=CURRENT_DATE();
";
$update_result = mysqli_query($conn, $update_query);
}
}
}
$API->disconnect();
}
?>
1.) You can start with "simplify" insert queries:
Just have some variable $INSERT_VALUES and do this in loops
$INSERT_VALUES.=", ('$service_id', '$bytes', CURRENT_DATE())";
After Loop, you can do only one Insert (only one query) to database:
$add_query = "INSERT INTO traffic_counters (service_id, upload_bytes, date) VALUES INSERT_VALUES";
2.) if you have LARGE amount of rows, using UPDATE is very bad idea, but at this type of using that, there is no way to solve this. You can Try call on mysql START TRANSACTION; and after all of updates, call COMMIT;
3.) On large database SELECT ... WHERE ... is slower than load all datas to php array and then find your needed row by array_search or by using good method of creating array (For example $DATA[service_id]["colunm"]=$value)
I've got the following code:
<?php
include 'payment/dbConfig.php';
$email = $_GET['email'];
$account = $_GET['account'];
if($email != ''){
$sql = "SELECT command FROM bots WHERE email='".$email."' AND account='".$account."' limit 1";;
$result = $db->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$value = $row["command"];
}
}
if($value != ''){
echo $value;
$sql = "UPDATE `bots` SET command='' WHERE email='".$email."' AND account='".$account."'";
$db->query($sql);
}else{
$sql = "INSERT INTO `bots`(`email`, `account`) VALUES ('".$email."','".$account."')";
$db->query($sql);
}
}
?>
Which definitely looks like a mess, and this isn't working right.
Specifically, it endlessly adds the same 'email' and 'account' into the database, even though it should be done only when $value is not equal to emptiness.
What should I do?
You can do this in less code.
if ($result->num_rows > 0) {
// Update
$sql = "UPDATE `bots` SET command='' WHERE email='".$email."' AND account='".$account."'";
$db->query($sql);
} else {
// Insert
$sql = "INSERT INTO `bots`(`email`, `account`) VALUES ('".$email."','".$account."')";
$db->query($sql);
}
Note: You are passing the user inputs ($_GET) directly in the query, Sanitize all user inputs ($_GET, $_POST) and check for SQL Injection before execute any query.
Please i would like to delete a record from a particular table and insert same record into another table. this is working fine if all the tables contain same columns but i need to add another column to the table where the deleted record is inserted.
here is my code thank you
<?php
// connect to the database
$con=mysqli_connect("localhost", "root", "");
if(mysqli_select_db($con, "e-office"));
$execute ='';
$Posting_User = mysqli_escape_string($con, $_SESSION[('Uname')]);
// confirm that the 'id' variable has been set
if (isset($_GET['execute'])) $execute = $_GET['execute'];
{
// get the 'id' variable from the URL
if($execute=='delete'){
$id = $_GET['id'];
// delete record from database
$sql = mysqli_query($con, "INSERT INTO tbl_income_approved SELECT * FROM
tbl_income WHERE (trn_no = '$id' AND Approved_by ='$Posting_User') ");
$sql = mysqli_query($con, "DELETE FROM tbl_income WHERE trn_no = '$id'");
if($sql)
// redirect user after delete is successful
header("Location: income_report.php");
else
// if the 'id' variable isn't set, redirect the user
echo "query not successful";
}
}
?>
To God be the glory! I have a working code now, thanks all
<?php
session_start();
if(!$_SESSION[('Uname')]){
header("location:login.php");
}
// connect to the database
$con=mysqli_connect("localhost", "root", "");
if(mysqli_select_db($con, "e-office"));
$execute ='';
$Posting_User = mysqli_escape_string($con, $_SESSION[('Uname')]);
// confirm that the 'id' variable has been set
if (isset($_GET['execute'])) $execute = $_GET['execute'];
{
$id = $_GET['id'];
///testing
$sql="SELECT * FROM tbl_income WHERE trn_no='$id'";
$result=mysqli_query($con, $sql);
//echo $count;
while($row = mysqli_fetch_assoc($result)){
$Posting_User = mysqli_escape_string($con, $row['Posting_User']);
$date = mysqli_escape_string($con, $row['date']);
$rno = mysqli_escape_string($con, $row['rno']);
$source = mysqli_escape_string($con, $row['source']);
$subsidiary = mysqli_escape_string($con, $row['subsidiary']);
$deposit = mysqli_escape_string($con, $row['deposit']);
$amount = mysqli_escape_string($con, $row['amount']);
$narration = mysqli_escape_string($con, $row['narration']);
$timestamp = mysqli_escape_string($con, $row['timestamp']);
$trn_no = mysqli_escape_string($con, $row['trn_no']);
$Approved_by = mysqli_escape_string($con, $_SESSION[('Uname')]);
$sql=mysqli_query($con, "INSERT INTO tbl_income_approved (Posting_User, date, rno, subsidiary, deposit, source, amount, narration, Approved_by) VALUES ('$Posting_User','$date','$rno', '$subsidiary', '$deposit', '$source', '$amount', '$narration', '$Approved_by')");
}
///close testing
// get the 'id' variable from the URL
if($execute=='delete'){
$id = $_GET['id'];
$sql = mysqli_query($con, "DELETE FROM tbl_income WHERE trn_no = '$id'");
if($sql)
// redirect user after delete is successful
header("Location: income_report.php");
else
// if the 'id' variable isn't set, redirect the user
echo "query not successful";
}
}
?>
I know how to fetch user data from database with the code below. Now I want to navigate to another page (using onclick) and to display this user data by id. This would be like StackOverflow or Facebook, when you click on a photo or ID, and the site takes you to the user's profile page.
Here is my code so far:
<?php
$connect = mysql_connect("localhost","root","") or die(mysql_error());
$select = mysql_select_db("profile") or die(mysql_error());
$result = mysql_query("SELECT * FROM users order by id DESC");
$id = $_SESSION['id'];
while($row = mysql_fetch_array($result)){
if($row['id'] !== $id){
echo "<table id='suggest'><tr><td id='frienddata'><a href='http://localhost/profile/userprofile.php'>".$row['first'].' '. $row['last']."<a/></td><br></tr></table>";
}
}
?>
$id = $_GET['id'];
if(!isset($id))
{
$connect = mysql_connect("localhost","root","") or die(mysql_error());
$select = mysql_select_db("profile") or die(mysql_error());
$result = mysql_query("SELECT * FROM users WHERE id = '"$id"'");
if(!$result)
{
die('user_not_found');
}
mysqli_fetch_row( $result );
echo "<table id='sugest'><tr><td id='frienddata'><a href='http://localhost/profile/userprofile.php'>".$row['first'].' '. $row['last']."<a/></td><br></tr></table>";
suppose you are in a page before clicking on a user profile,the link should be some thing like this 'site.com/userprofile.php?id=5'.
now in userprofile.php:
$id = $_GET['id'];
if(!isset($id))
die('user not found');
$connect = mysql_connect("localhost","root","") or die(mysql_error());
$select = mysql_select_db("profile") or die(mysql_error());
$result = mysql_query("SELECT * FROM users where id='".$id."'");
if (!$result) {
die('user not found');
}
$row = mysql_fetch_row($result);
echo "<table id='sugest'><tr><td id='frienddata'><a href='http://localhost/profile/userprofile.php'>".$row['first'].' '. $row['last']."<a/></td><br></tr></table>";
I want to load an xml file into a table column with MySQL. How do I do this with an INSERT statement instead of an UPDATE statement?
This code does an INSERT to create a new row, gets the id for the last inserted row, then attempts to do the update to load the xml file. But it doesn't update the row with the xml info.
I would like to know what to fix to put the xml in the database column. I also want to streamline the code and do the LOAD_FILE in one INSERT statement.
MySQL database table structure
Field Datatype Attributes Extra
userid INT(6) unsigned auto_increment
user_events LONGTEXT
PHP code to add xml file
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("hostname","adminuser","adminpassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test_db", $con);
$qinsert = "INSERT INTO load_xml (`user_events`) VALUES ('user events')";
$result_insert = mysql_query($qinsert);
$qtext = "SELECT * FROM load_xml";
$result = mysql_query($qtext);
$numrows = mysql_num_rows ( $result );
while ($row = mysql_fetch_row($result)) {
echo 'user id '.$row[0].' user_events '.$row[1].'<br/>';
}
$insert_id = "SELECT LAST_INSERT_ID()";
$rin_id = mysql_query($insert_id);
$row = mysql_fetch_row($rin_id);
$userid = $row[0];
echo 'last added id '.$userid.'<br/>';
$update_xml = "UPDATE load_xml SET user_events=LOAD_FILE('my_events.xml') WHERE userid='$userid'";
$result_update = mysql_query($update_xml);
$qtext = "SELECT * FROM load_xml";
$result = mysql_query($qtext);
$numrows = mysql_num_rows ( $result );
echo $numrows.'<br/>';
while ($row = mysql_fetch_row($result)) {
echo 'user_id '.$row[0].' user_events '.$row[1].'<br/>';
}
mysql_close($con);
?>
Just add the file in the original insert. The file path is that of a file on the server. The mysql user used to connect must have the file privilege. It must be the full path. On windows you need to replace back slashes with forward slashes -
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("hostname","adminuser","adminpassword");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test_db", $con);
$qinsert = "INSERT INTO load_xml (`user_events`) VALUES (LOAD_FILE('/full/path/to/my_events.xml'))";
$result_insert = mysql_query($qinsert);
$userid = mysql_insert_id();
echo 'last added id '.$userid.'<br/>';
$qtext = "SELECT * FROM load_xml";
$result = mysql_query($qtext);
$numrows = mysql_num_rows ( $result );
while ($row = mysql_fetch_row($result)) {
echo 'user id '.$row[0].' user_events '.$row[1].'<br/>';
}
mysql_close($con);
?>
UPDATE - here is another version using PDO prepared statement and file_get_contents() -
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db = new PDO('mysql:dbname=test_db;host=hostname', 'adminuser', 'adminpassword');
$qinsert = "INSERT INTO load_xml (`user_events`) VALUES (?)";
$stmt = $db->prepare($qinsert);
$stmt->execute(array(file_get_contents('my_events.xml')));
?>