This is my code:
if ((isset($_POST['vidcode'])) && (strlen(trim($_POST['vidcode'])) > 0)) {$vidcode = stripslashes(strip_tags($_POST['vidcode']));} else {$vidcode = 'Invalid URL';};
if ((isset($_POST['vidtitle'])) && (strlen(trim($_POST['vidtitle'])) > 0)) {$vidtitle = stripslashes(strip_tags($_POST['vidtitle']));} else {$vidtitle = 'No Title';};
$vidcode = str_replace('"', '', $vidcode);$vidcode = str_replace("'", "", $vidcode);$vidtitle = str_replace('"', '', $vidtitle);$vidtitle = str_replace("'", "", $vidtitle);
$db_handle = mysql_connect($server, $user_name, $password);$db_found = mysql_select_db($database, $db_handle);
$SQL = "SELECT status FROM youtube2mp3 WHERE videocode = '$vidcode' ";$result = mysql_query($SQL); [BUGFIX:Added]$row = mysql_fetch_assoc($result);[/BUGFIX]
if(mysql_num_rows($result) != false){
// Add to DB & Set Status
$SQL = "UPDATE youtube2mp3 SET status='Download Complete' WHERE videocode='$vidcode'";
$result = mysql_query($SQL);
[BUGFIX:Removed]
// Get Data into variable
$row = mysql_fetch_assoc($result);
[/BUGFIX]
// Check if its been processed
if (strcasecmp($row['status'], "Done") != 0){
// Add to DB & Set Status
$SQL = "UPDATE youtube2mp3 SET status='Initializing Conversion' WHERE videocode='$vidcode'";
$result = mysql_query($SQL);
$filename = $vidcode.'.mp4';
if (!file_exists($filename) && !filesize($filename) >= 10000) {
$SQL = "UPDATE youtube2mp3 SET status='Invalid' WHERE videocode='$vidcode'";
$result = mysql_query($SQL);
} else {
$SQL = "UPDATE youtube2mp3 SET status='Converting' WHERE videocode='$vidcode'";
$result = mysql_query($SQL);
//convert file
exec('ffmpeg -i '.escapeshellarg($vidcode).'.mp4 -ab 156 -f mp3 '.escapeshellarg($vidtitle).'.mp3 2>&1');
$SQL = "UPDATE youtube2mp3 SET status='Zipping' WHERE videocode='$vidcode'";
$result = mysql_query($SQL);
// Zip it up
exec('zip "zips/'.$vidcode.'.zip" "'.$vidtitle.'.mp3"');
//delete files
//unlink($vidcode.'.mp4');
unlink($vidtitle.'.mp3');
$SQL = "UPDATE youtube2mp3 SET status='Done' WHERE videocode='$vidcode'";
$result = mysql_query($SQL);
};
};
};
mysql_close($db_handle);
Right Just FYI - It was me being stupid! I reused $result which gave unexpected results. See [BUGFIX] in code above...
Don't use SELECT *..., explicitly list your columns in your queries. This way, it is clear what columns you expect to get from the database by looking at your code. Plus, if it turns out that a column you think exists does not, you'll get an error at the stage where the problem is actually happening - at the data retrieval, instead of later in your code when you're trying to use the data.
Also note, your use of mysql_fetch_array (docs) is returning a numerically-indexed array of columns. Use mysql_fetch_assoc (docs) for an associative array.
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$sql = '
SELECT
`status`,
`some_other_field`
FROM
`table`
WHERE
`videocode` = "'.$vidcode.'"';
$result = mysql_query($sql, $db_handle) or die('Error while performing query: '.mysql_error($db_handle));
if (mysql_num_rows($result, $db_handle) < 1) {
// you didn't get any rows back...
}
if(mysql_num_rows($result) != false){
// Get Data into variable
$row = mysql_fetch_assoc($result, $db_handle);
// Check if its been processed
if ($row['status'] != "Done"){
// CODE HERE IS STILL GETTING EXECUTED EVEN WHEN $row['status'] IS "Done"
}
}
Using this code, if the columns you try to select don't exist, then you'll get a database error.
I haven't read thoroughly what the problem is, in general you can:
Try this:
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('log_errors', 1);
ini_set('error_log', 'error_log.txt');
Try alert(response), I mean the the xml http response, it is not true that ajax has no output, ajax will bring the output exactly with all php errors if any! If you use jquery I guess there is something analogous to http response.
When code is executed in strange places, the solution is trivial just put echo inside every if, every else, every function, constructor whatever... As soon you see a block of code is alive when was supposed not to be focus there only!
When you suspect a problem in a very specific place but instead you focus in a big piece of code (as in your case) then in most case you have to forget all the rest of the code, it's not going to be of any help. Sorry if it is too general!
You are using mysql_fetch_array which returns the row as a 0 indexed array.
You need to use mysql_fetch_assoc
Try this:
if ((isset($_POST['vidcode'])) && (strlen(trim($_POST['vidcode'])) > 0)) {
$vidcode = stripslashes(strip_tags($_POST['vidcode']));
} else {
$vidcode = 'Invalid URL';
};
if ((isset($_POST['vidtitle'])) && (strlen(trim($_POST['vidtitle'])) > 0)) {
$vidtitle = stripslashes(strip_tags($_POST['vidtitle']));
} else {
$vidtitle = 'No Title';
};
$vidcode = str_replace('"', '', $vidcode);
$vidcode = str_replace("'", "", $vidcode);
$vidtitle = str_replace('"', '', $vidtitle);
$vidtitle = str_replace("'", "", $vidtitle);
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$SQL = "SELECT * FROM table WHERE videocode = '$vidcode' ";
$result = mysql_query($SQL);
if(mysql_num_rows($result) != false) {
// Get Data into variable
$row = mysql_fetch_assoc($result);
// Check if its been processed
if (strcasecmp($row['status'], "Done") != 0)
{
// CODE HERE IS STILL GETTING EXECUTED EVEN WHEN $row['status'] IS "Done"
}
};
};
mysql_close($db_handle);
Maybe try this:
if(strcasecmp(trim($row['status']), "DONE") != 0) {
Or try the while loop
function validatePostValues($alt_response = 'Default', $post_value = NULL) {
if((isset($post_value)) && (strlen(trim($post_value)) > 0)) {
$return_value = stripslashes(strip_tags($post_value));
$return_value = str_replace('"', '', $return_value);
$return_value = str_replace("'", "", $return_value);
} else {
$return_value = $alt_response;
}
return $return_value;
}
$vidcode = validatePostValues('Invalid URL', $_POST['vidcode']);
$vidtitle = validatePostValues('No Title', $_POST['vidtitle']);
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$SQL = "SELECT * FROM table WHERE videocode = '$vidcode' ";
$result = mysql_query($SQL);
if(mysql_num_rows($result)) {
// Loop through the results
while($row = mysql_fetch_assoc($result)) {
// Added for debugging, enclose w/ PIPE for
// whitespace check
echo "Status is: |".$row['status']."|<br />\n";
// Check if its been processed
if($row['status'] != "Done"){
// CODE HERE IS STILL GETTING EXECUTED
// EVEN WHEN $row['status'] IS "Done"
echo "Row: ".print_r($row,true)."<br />\n";
}
}
}
mysql_close($db_handle);
Related
So I thought this would be a simple query to just delete rows that didn't have any data stored under certain columns, but for some reason my query is returning that zero rows have been deleted, I checked the table and they are still there.
What I want to do is delete from my gps_routes table where the route_lat and route_long do not contain a location (empty).
I have checked my to make sure I have delete permissions enabled as well.
$sql = "SELECT * FROM gps_routes";
$result = $link->query($sql);
$rowCount = $result->num_rows; $rows_deleted = 0; $delete_row = false;
if ($rowCount > 0)
{
while($row = $result->fetch_assoc())
{
$user = $row['user_email'];
$id = $row['route_id'];
$lat = $row['route_lat'];
$lng = $row['route_long'];
if (empty($lat) || empty($lng)){
$delete_row = true;
}
if (ctype_space($lat) || strlen(trim($lat)) == 0){
$delete_row = true;
}
if ($lat == '' || $lat == ""){
$delete_row = true;
}
if ($delete_row){
$rows_deleted++;
mysqli_query($link, "DELETE FROM gps_routes WHERE user_email = '$user' AND route_id = '$id'");
}
}
echo "Routes deleted: $rows_deleted";
}
From your code is suggest that you just want to go through your DB and check to see if the lat and long are empty. If they are then delete them.
Sounds like you can just use this query to get the job done.
mysqli_query($link, "DELETE FROM gps_routes WHERE (route_lat = '' OR route_lat IS NULL) OR (route_long = '' OR route_long IS NULL)");
This is how I would do it based off the code you have provided:
$query = "DELETE FROM gps_routes WHERE (route_lat = '' OR route_lat IS NULL) OR (route_long = '' OR route_long IS NULL)";
$result = $link->query($query);
echo 'Routes deleted: ' . $result->num_rows;
Current update: I've cleaned up the code, and there are still some issues.
NOTE this code runs every 3 seconds. The outermost 'else' statement seems to run, setting the time to 0 in the database table, but then there is no activity.
After the initial time of running, the outermost 'else' statement should never run, and the time value stored under the user's alias should keep updating with the latest time stamp, but it just sits at '0'.
This is the JS that runs the php file:
//CHECK FOR NEW CHAT MESSAGES
setInterval(function()
{
$.post("chat_update.php", function(data) { $("#rect_comments_text").append(data);} );
}, 3000);
Code:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$time_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$timestamp = time();
$last_time_query = "SELECT alias FROM $time_table";
$last_time_result = mysqli_query($connection,$last_time_query);
$last_time_rows = mysqli_fetch_array($last_time_result);
if ($last_time_rows['alias'] === $alias)
{
$last_time = $last_time_rows['time'];
$query = "SELECT * FROM $table WHERE time > $last_time ORDER BY text_id ASC"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
//APPEND NEW MESSAGES
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
}
//UPDATE LAST SYNC TIME
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
echo '<p> HERE </p>';
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','0')";
mysqli_query($connection,$update_query);
}
?>
You try this
$sql_update = "UPDATE time_table SET time= '$timestamp' WHERE alias = '$alias'";
if ($con->query($sql_update ) === TRUE) {
}
else{
echo "Error: " . $sql_update . "<br>" . $con->error;
}
You need to only check mysqli_num_rows to whether to insert or update data. You have to add ' around $alias in select query also. change your code as below:
//EITHER UPDATE THE EXISTING VALUE OR CREATE ONE FOR FIRST TIME VISITORS...
$last_time_query = "SELECT * FROM $time_table WHERE alias = '$alias'"; //change here add '
$last_time_result = mysqli_query($connection,$last_time_query);
if (mysqli_num_rows($last_time_result) == 0) //Only check number of rows
{
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','$timestamp')";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
So I installed this jackpot script with a layout and everything and within the jackpot script there was a set.php file which I tried to set up, it looked like this:
<?php
$sitename = "csgoxd.net";
$link = #mysql_connect("localhost:3306", "csgoxdne", "thisisasecretpassword");
$db_selected = mysql_select_db('csgoxdne_csgoxddb', $link);
mysql_query("SET NAMES utf8");
function fetchinfo($rowname,$tablename,$finder,$findervalue) {
if($finder == "1") $result = mysql_query("SELECT $rowname FROM $tablename");
else $result = mysql_query("SELECT $rowname FROM $tablename WHERE `$finder`='$findervalue'") or die (mysql_error());
$row = mysql_fetch_assoc($result);
return $row[$rowname];
}
?>
So I'm new when it comes to coding in general (I know some basic stuff but that's it) so basically I'm not sure if I'm supposed to fill out more of this file because I get this error on my website.
"Table 'csgoxdne_csgoxddb.info' doesn't exist"
I'm new to this and I'm trying to learn so help is much appreciated.
You should use MySQLi to make use of its advantages it offers over MySQL. You can see more here.
The script you have isn't all too bad, but it does need some tweaking. It's vulnerable to injection like Marc B said. I'm going to assume that csgoxdne_csgoxddb is your table name.
Try this:
<?php
$mysqli = new mysqli("localhost:3306", "csgoxdne", "thisisasecretpassword");
if (mysqli -> error){ print ("Error connecting! Message: ".$mysqli->error); }
mysqli_set_charset($mysqli, 'utf8');
function fetchinfo($rowname, $tablename, $finder, $findervalue) {
if ($finder == "1") {
$query = "SELECT * FROM $tablename WHERE rowname = '$rowname'";
$result = mysqli_query($mysqli, $query);
} else {
$query = "SELECT * FROM $tablename WHERE `$finder`='$findervalue'";
if (!$query) {
die('Invalid query: ' . $mysqli->error);
}
$result = mysqli_query($mysqli, $query);
}
return $result;
}
?>
Oh and make sure the port number on your localhost is correct.
Also to go through the values of result you can use:
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
#do things
}
}
I have the following code to insert if a row doesn't exist with the given part_code or update if the part_code already exists. The problem is that it always inserts and produces duplicates. Can anyone see why.
$query = 'SELECT * FROM qty_csv';
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
while($row = mysqli_fetch_array($result)){
$part_code = $row['code'];
$part_descr = $row['descr'];
$part_qty_in_stock = $row['qty_in_stock'];
$reorder_level = $row['reorder_level'];
$reorder_qty = $row['reorder_qty'];
$part_price = $row['price'];
// check to see if the value you are entering is already there
$result1 = $conn->query("SELECT * FROM part WHERE part_code == '$part_code'");
if (!$result1){
$sql =
"INSERT INTO part VALUES (
'',
'',
'$part_descr',
'$part_price',
'',
'$part_code',
'',
'',
'',
'',
'$reorder_level',
'$reorder_qty',
'',
'',
'$part_qty_in_stock',
'',
'',
''
)";
if (!$conn->query($sql)) {
echo "INSERT failed: (' . $conn->errno . ') " . $conn->error;
}
}else{
$sql = "UPDATE part SET "
. "part_qty_in_stock = '$part_qty_in_stock',"
. "reorder_level = '$reorder_level',"
. "reorder_qty = '$reorder_qty' "
. "WHERE part_code == '$part_code'";
// This code exists and will be updated
$conn->query($sql);
}
}
I have it under the debugger and see that even if part_code == '$part_code' the $result1 is bool()false. I would have expected it to be true.
The problem here is that your "$result1" object is False only when an error happens, otherwise, even if the query returns no results (because it's empty), it will be a mysqly object.
You should check the number of rows rather than just checking !$result.
Just change
if (!$result1){
with
if (mysqli_num_rows($result1) == 0){
Check out the docs for more info:
http://it1.php.net/mysqli_query
http://www.php.net/manual/en/mysqli-result.num-rows.php
please check your query,please use = for checking instead of ==
SELECT * FROM part WHERE part_code = '$part_code'
Use
$result1 = $conn->query("SELECT count(*) as count FROM part WHERE part_code = '$part_code'");
Then simply check $result1['count'] > 0
I must be missing something simple but I don't see it. The following code works great.
<?php
$res = mysql_connect("localhost", "newuser", "");
mysql_select_db("supplydb");
function filter($data)
{
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);
return $data;
}
error_reporting(0);
require("../codebase/grid_connector.php");
$mask5 = filter($_GET["var1"]);
//Get Category ID
$cat = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id='$mask5'");
$rows = mysql_fetch_array($cat, MYSQL_ASSOC);
$array = filter($rows['category']);
//Get Manufactuer ID
$man = mysql_query("SELECT manufacturer_id FROM submissions WHERE submissions.submission_id='$mask5'");
$arows = mysql_fetch_array($man, MYSQL_ASSOC);
$array1 = filter($arows['manufacturer_id']);
function formatting($row)
{
$data = $row->get_value("fda_approved");
if ($data == 1)
$row->set_value("fda_approved", Yes);
else
$row->set_value("fda_approved", No);
}
$gridConn = new GridConnector($res, "MySQL");
function myUpdate($action)
{
$data6 = $action->get_id();
$cat_id = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id ='{$data6}'") or die("Error in query: $query. " . mysql_error());
$rows56 = mysql_fetch_array($cat_id, MYSQL_ASSOC);
$array = filter($rows56['category']);
$status = $action->get_value("approval_status");
$gridConn = new GridConnector($res, "MySQL");
mysql_query("UPDATE submissions SET approval_status='{$status}' WHERE submissions.submission_id='{$data6}'") or die("Error in query: $query. " . mysql_error());
$action->success;
}
$gridConn->event->attach("beforeUpdate", "myUpdate");
$gridConn->event->attach("beforeRender", "formatting");
$gridConn->render_sql("SELECT * FROM submissions JOIN products ON products.product_id = submissions.product_id and submissions.category='$array' and submissions.manufacturer_id='$array1' and submissions.approval_status='0'", "submission_id", "item_number,description,list_price,sugg_price,quantity_per_unit,fda_approved,gpo_contract_number, approval_status");
?>
This code does not
<?php
require("../site_globals/dbc_simple.php");
//$res = mysql_connect("localhost", "newuser", "");
//mysql_select_db("supplydb");
error_reporting(0);
require("../codebase/grid_connector.php");
$mask5 = filter($_GET["var1"]);
//Get Category ID
$cat = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id='$mask5'");
$rows = mysql_fetch_array($cat, MYSQL_ASSOC);
$array = filter($rows['category']);
//Get Manufactuer ID
$man = mysql_query("SELECT manufacturer_id FROM submissions WHERE submissions.submission_id='$mask5'");
$arows = mysql_fetch_array($man, MYSQL_ASSOC);
$array1 = filter($arows['manufacturer_id']);
function formatting($row)
{
$data = $row->get_value("fda_approved");
if ($data == 1)
$row->set_value("fda_approved", Yes);
else
$row->set_value("fda_approved", No);
}
$gridConn = new GridConnector($res, "MySQL");
function myUpdate($action)
{
$data6 = $action->get_id();
$cat_id = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id ='{$data6}'") or die("Error in query: $query. " . mysql_error());
$rows56 = mysql_fetch_array($cat_id, MYSQL_ASSOC);
$array = filter($rows56['category']);
$status = $action->get_value("approval_status");
$gridConn = new GridConnector($res, "MySQL");
mysql_query("UPDATE submissions SET approval_status='{$status}' WHERE submissions.submission_id='{$data6}'") or die("Error in query: $query. " . mysql_error());
$action->success;
}
$gridConn->event->attach("beforeUpdate", "myUpdate");
$gridConn->event->attach("beforeRender", "formatting");
$gridConn->render_sql("SELECT * FROM submissions JOIN products ON products.product_id = submissions.product_id and submissions.category='$array' and submissions.manufacturer_id='$array1' and submissions.approval_status='0'", "submission_id", "item_number,description,list_price,sugg_price,quantity_per_unit,fda_approved,gpo_contract_number, approval_status");
?>
The only difference is the include file at the top and all the include file is is:
<?php
$res = mysql_connect("localhost", "newuser", "");
mysql_select_db("supplydb");
?>
Im fairly new to php but this seems simple and I'm not sure what is getting lost in translation. This works fine on other pages by the way so it must have something to do with the $gridConn = new GridConnector($res, "MySQL"); but I dont know enough to see what. I'm using the DHTMLX javascript library. Could it have something to do with that? Ive tried everything here. Ideas?
Im getting: XML Parsing Error: XML or text declaration not at start of entity Location
Problem is not in the database connection itself, it works correctly and generates data, but result xml corrupted, because some output was started before connector's code.
Check ../site_globals/dbc_simple.php - probably it have some whitespaces|newlines after closing "?>" tag - delete them and it will fix the problem.
Such whitespaces|newlines will not cause harm for HTML pages, but for XML data any extra char at start of document can cause a problem.