new to mysql question php - php

I have a table in my database that looks like this:
|id|team_name|team_url|xml|
I have a cronjob that calls a script. In this script, I want to use my class to check if the url exists, and if it doesn't, delete the entry in the database. Something like this:
foreach row in table, if (Security::checkUrl(team_url)), delete entry. else: update xml.
How can I do something like this? I don't need help with the url verification only the mysql query and how i should go through each row and delete the rows where the url is invalid.
Thanks.

The mysql query to delete the row would be
DELETE FROM tablename WHERE team_url = '$team_url';
$team_url is the php variable which has the team_url value.
The above command will delete all rows where the team_url matches $team_url.
What you will want to do is in php loop through all the rows and check their URL.
$query = "SELECT * FROM tablename";
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
if (Security::checkUrl($row['team_url'])) {
$res = mysql_query("DELETE FROM tablename WHERE team_url = '".mysql_real_escape_string($row['team_url'])."'");
}
else {
//update xml
}
}
mysql_free_result($result);
The above code is just a sample and not to be used in production without proper sql injection cleaning / checking.

To delete a row with a given URL, prepare a query like 'DELETE FROM table WHERE team_url=?' with, e.g.,
mysqli_stmt::prepare(). Then bind the URL that you want to delete to the parameter with mysqli_stmt::bind_param(), à la bind_param("s", $dead_url). Then execute the statement using mysqli_stmt::execute().
EDIT: per strager's suggestion: the mysqli reference in the PHP manual is here: http://php.net/manual/en/book.mysqli.php. It has links to documentation for all the functions that I just mentioned.

Related

Check if value is found in SQL table within PHP script?

I need to be able to check and see in a certain string is anywhere within my SQL table. The table I am using only has one column of char's. Right now it is saying that everything entered is already within the table, even when it actually is not.
Within SQL I am getting the rows that have the word using this:
SELECT * FROM ADDRESSES WHERE STREET LIKE '%streeetName%';
However, in PHP the word is being entered by the user, and then I am storing it as a variable, and then trying to figure out a way to see if that variable is somewhere within the table.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one of each address allowed.<br /><hr>";
}
You need to do a little bit more than building the query, as mysql_query only returns the resource, which doesn't give you any information about the actual result. Using something like mysql_num_rows should work.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(mysql_num_rows($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
Note: the mysql_* functions are deprecated and even removed in PHP 7. You should use PDO instead.
In the SQL you used
%streeetName%
But in the query string below, you used
%$streeetName%
Change the correct one
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
if($results->num_rows) is what you need to check if you have results back from your query. An example of connection and query, check, then print or error handle, the code is loose and not checked for errors. Best of luck...
//Typically your db connect will come from an includes and/or class User...
$db = new mysqli('localhost','user','pass','database');
$sql = "SELECT * FROM `addresses` WHERE `street_name` LIKE '%$streetName%'",$connect;
//test your queries in PHPMyAdmin SQL to make sure they are properly configured.
//store the results of your query in a variable
$results = $db->query($sql);
$stmt = '';//empty variable to hold the values of the query as it runs through the while loop
###########################################################
#check to see if you received results back from your query#
###########################################################
if($results->num_rows){
//loop through your results and echo or assign the values as needed
while($row = $results->fetch_assoc()){
echo "Street Name: ".$row['STREET_NAME'];
//define more variables from your DB query using the $row[] array.
//concatenate values to a variable for printing in your choice further down the document.
$address .= $row['STREET_NAME'].' '.$row['CITY'].' '$row['STATE'].' '$row['ZIP'];
}
}else{ ERROR HANDLING }

Calling stored procedures from PHP, with a PHP variable as the IN parameter

I have tables that look like this:
I have a procedure that I am trying to use to get all the SubCategoryNames that have the same CategoryID as a given CategoryName: this one:
CREATE PROCEDURE getSubCategory(IN category TEXT) READS SQL DATA
BEGIN
SELECT `SubCategoryName` FROM `sub_category` WHERE `CategoryID` = (SELECT `CategoryID` FROM `category` WHERE `CategoryName` = category);
END
For some reason, when I try to call this procedure from the PHP code, with a PHP variable, like so:
$result = $connection->query($connection->real_escape_string("CALL `jcarillo_db`.getSubCategories(" . $superCategory . ")"));
// based on that, print the appropriate menu
if ($result)
{
// print an <option> for each row in the result set (remember, $result will have one entry per row!)
while ($row = $result->fetch_row())
{
require_once("argumentParser.php");
printf('<option name="%sOption" value="%s">%s</option>\n', toCamelCase($row[0]), $row[0], $row[0]);
}
// don't forget to free result set!
$result->close();
}
else
{
echo "Fetch failed(" . $connection->errno . ")" . $connection->error;
}
The "Fetch failed" gets echoed, instead of the results! Yet, for some reason, when I try to call that very same stored procedure from the database (namely, through phpMyAdmin), it works! What the heck am I doing wrong?!?! $connection is set up correctly, and I know this because my attempt to echo the CategoryNames from the category table works with it!
The problem here is that you are trying to call the function with a String parameter and you are passing it without letting the MySQL knowing its a string.
Try this instead:
$result = $connection->query("CALL `jcarillo_db`.getSubCategories('".$connection->real_escape_string($superCategory)."')");

Obtain resource from POST php

Lets say I have a database full of info, and I want the user to find his info by inputting his ID. I collect the input of the user with:
'$_POST[PID]'
And want to put it into a resource variable like:
resource $result = '$_POST[PID]';
In order to print out their information like :
while($row = mysql_fetch_array($result))
{
echo all their information
echo "<br>";
}
However I cannot create the resource variable because it is telling me that it is a boolean. How can I fetch that resource in order to print the list?
Several problems with this
First, a resource is something like a database result set, a connection (like fsockopen), etc. You can't just declare or typecast a variable into a result set
Second, you need to do something like SQL to fetch the data based on that ID. That involves connecting to the DB, running your query and then doing your fetch_array
Third, mysql_ functions are depreciated. Consider using mysqli instead.
I think you're having problems displaying the result set.
Try this
$id = $_POST['PID'];
$result = "SELECT * FROM table WHERE id ='.$id.'";
while($row = mysqli_query($result))
{
echo $row[0]; //or whichever column you want to display.
//$row[0] will display your
// PK
}

echo statement not showing result after getting variable from $_post in php mysql

I am unable to understand why I am unable to use echo statement properly here.
Link which passes get value to script
http://example.com/example.php?page=2&hot=1002
Below is my script which takes GET values from link.
<?php
session_start();
require('all_functions.php');
if (!check_valid_user())
{
html_header("example", "");
}
else
{
html_header("example", "Welcome " . $_SESSION['valid_user']);
}
require('cat_body.php');
footer();
?>
cat_body.php is as follows:
<?php
require_once("config.php");
$hot = $_GET['hot'];
$result = mysql_query( "select * from cat, cat_images where cat_ID=$hot");
echo $result['cat_name'];
?>
Please help me.
mysql_query returns result resource on success (or false on error), not the data. To get data you need to use fetch functions like mysql_fetch_assoc() which returns array with column names as array keys.
$result = mysql_query( "select
* from cat, cat_images
where
cat_ID=$hot");
if ($result) {
$row = mysql_fetch_assoc($result);
echo $row['cat_name'];
} else {
// error in query
echo mysql_error();
}
// addition
Your query is poorly defined. Firstly there is not relation defined between two tables in where clause.
Secondly (and this is why you get that message "Column 'cat_ID' in where clause is ambiguous"), both tables have column cat_ID but you did not explicitly told mysql which table's column you are using.
The query should look something like this (may not be the thing you need, so change it appropriately):
"SELECT * FROM cat, cat_images
WHERE cat.cat_ID = cat_images.cat_ID AND cat.cat_ID = " . $hot;
the cat.cat_ID = cat_images.cat_ID part in where tells that those two tables are joined by combining rows where those columns are same.
Also, be careful when inserting queries with GET/POST data directly. Read more about (My)Sql injection.
Mysql functions are deprecated and will soon be completely removed from PHP, you should think about switching to MySQLi or PDO.

Deceptively Simple: Check If Data Is Returned From MySQL In One Query

Here is a simple scenario I am contemplating. I have a query that is executed on a MySQL database from PHP. I would like to check if any data was returned from the query. However, in order to perform that check, it pulls out one of the rows of returned data.
Look at this example, and its comments:
$booksGrabber = ("SELECT * FROM table");
if (!$booksGrabber) {
//Query failed, perhaps a syntax error
exit;
}
if (!mysql_result($booksGrabber, 0)) {
//No data was returned :(
exit;
}
while ($book = mysql_fetch_assoc($booksGrabber)) {
//mysql_result() stole the first row of returned data
//So if I was expecting the loop to display 4 results,
//I only get 3...
}
How can I check if data was returned from the database without running two queries (one to check, the other to display all of the data) or having one of the rows stolen?
Use mysql_num_rows. It was as simple as it looked.
EDIT: If you want more complicated, add mysql_data_seek($booksGrabber,0).
Simple: mysql_query() function that runs the query will return false on error and then you can use mysql_num_rows() for the count. So you can do something like:
$result = mysql_query('SELECT * FROM table');
if (!$result) {
print('Invalid query: ' . mysql_error());
} elseif (mysql_num_rows() == 0) {
print("no results");
} else {
// You can use safely data from the query :)
}

Categories