So i'm trying to use in_array to call a list back from the database and then i'm checking with those results to see if the field "Title" is present in the array by doing the following.
$qGetAllTitles = "SELECT ArticleTitle FROM articles
UNION
SELECT ArticleTitle FROM temp_article";
$rGetAllTitles = mysqli_query($dbc, $qGetAllTitles);
$GetAllTitlesRow = mysqli_fetch_array($rGetAllTitles, MYSQLI_ASSOC);
if (in_array($Title, $GetAllTitlesRow['ArticleTitle'])){
$errors[0] = "The title is already taken by another article, please pick a different title";
} else {
$TTL = mysqli_escape_string($dbc, trim($Title));
$errors[0] = "Title worked";
}
I'm aware that the strings are case sensitive (and i'm looking how to negate this but that's another unrelated question)
My problem is, when i put an already used article title into the title field (which works, all other checks i use work, just not this one) it still returns "title worked", even though the check shouldn't unless the title is unique.
I've checked the SQL input in phpmyadmin (for my MySQL database) and that works getting all (3) results and the method of fetching the query is reused from elsewhere in my code, which also works, same as the in_array check so i'm really not sure why it's not working.
Your query returns multiple rows but you are only retrieving data for the first row. So unless the title matches the first row's title you won't find any duplicates. You need to do one of the following:
1) Loop through the result set and make an array of page titles before using in_array()
$GetAllTitlesRows = array();
while ($row = mysqli_fetch_array($rGetAllTitles, MYSQLI_ASSOC)) {
$GetAllTitlesRows[] = $row['ArticleTitle'];
}
or
2) Just search for any articles using that title right in your query which makes the code a whole lot simpler (recommended). In other words, use a WHERE clause specifically looking for that title in the ArticleTitle field. If you get any results you know it is taken.
$qGetAllTitles = "SELECT ArticleTitle FROM articles WHERE ArticleTitle = '$Title'
UNION
SELECT ArticleTitle FROM temp_article WHERE ArticleTitle = '$Title'";
$rGetAllTitles = mysqli_query($dbc, $qGetAllTitles);
if (mysqli_num_rows($rGetAllTitles) > 0){
$errors[0] = "The title is already taken by another article, please pick a different title";
}
Related
I'm trying to place one mysql select inside another one and combine the results to be displayed.
this is my code:
$allattrs = "";
$sql69 = "SELECT * FROM product_details";
$query69 = mysqli_query($db_conx, $sql69);
$login_check69 = mysqli_num_rows($query69);
if($login_check69 > 0){
while($row69 = mysqli_fetch_array($query69, MYSQLI_ASSOC)){
$FID = $row69["id"];
$sql2s = "SELECT * FROM ATTRIBUTES WHERE id='$FID'";
$query2s = mysqli_query($db_conx, $sql2s);
$login_check2s = mysqli_num_rows($query2s);
if($login_check2s > 0){
while($row2s = mysqli_fetch_array($query2s, MYSQLI_ASSOC)){
// Get member ID into a session variable
$Sid = $row2s["id"];
$attr = $row2s["attr"];
$allattrs .= ''.$attr.', ';
}
}
$product_list .= '<tr>
<td>'.$allattrs.'</td>
</tr>';
}
}
The problem i'm having is that the $allattrs returns the values but it will put everthing together.
for example:
if one attr column in mysql database has apples, and another one has oranges, when i see the results of $allattrs on my PHP page i see this:
id 1 - apples
id 2 - apples, oranges
id 3 - apples, oranges, apples, oranges
etc etc
this is in fact wrong as each attribute value needs to stay true to their own id and product_details id field!
I'm not sure what I am doing wrong to cause this.
could someone please advise on this issue?
any help would be appreciated.
The right way to write your query is using JOIN, EXISTS, or IN. I think you would find this most natural:
SELECT a.id, GROUP_CONCAT(a.attr) as attrs
FROM ATTRIBUTES a
WHERE a.id IN (SELECT id FROM product_details)
GROUP BY a.id;
This replaces a bunch of your code.
Looks like you are only interested in the the attributes then try this out instead of the first sql:
SELECT * FROM ATTRIBUTES where id IN (SELECT id FROM product_details)
You need to set $allattrs to an empty string inside your first while loop, instead of only once before.
Apart from that, you should look into the following two topics: Normalization and JOINs.
Just a little assistance, This is a pretty simple problem but it doesn't seem to work right. I am just comparing the value in a variable with all the values in a sql column. Same as if I were to compare a username input to the list of usernames in a sql column. This however is just to compare that the item id being stored in the column for that row is not an item id that is already in use.
I tested the value that I am getting back from the sql query and it is equal to the item id I typed in the input. What you will see below is the actual test to see if the id I am getting back is the one that I am looking for as well as the id of the row I can find that value in. The results I get is
2, 000002 (which is correct) that is what I am looking for.
$itemId = $_POST['itemId'];
if($sqlItemId = $dbCon->query("SELECT * FROM CVCinStoreCoins WHERE itemId = '$itemId'")){
while($data = $sqlItemId->fetch_assoc()){
printf("<p>%s, %s</p>", $data['id'], $data['itemId']);
die();
}
Then I took this out and tried to compare the value in the variable which is the same itemId already stored (000002). that is where I am going wrong.
I modified the code to look like this for further testing. Seems straight forward yet i am getting a FALSE response providing the latter echo statement "Item Id is not in use" But it is in the DB. I tried it a few different ways based on what I read in stackoverflow but none are giving me the right answer.
$sqlItemId = $dbCon->query("SELECT * FROM CVCinStoreCoins WHERE itemId = '$itemId'");
if($itemId == $sqlItemId){
echo "This item id is already in use. \n";
die();
} else {
echo "Item Id is not in use:";
die();
}
At one point I even tried a while statement to fetch the associated values prior to testing it but that didn't turn up a positive result either. Any suggestions?
Inside $sqlItemId you have the full table row (if any), not only its ID; change the SQL into a count and check the number of rows returned (if greater than 0 you have a duplicate):
$rowsCount = $dbCon->query("
SELECT COUNT(*)
FROM CVCinStoreCoins
WHERE itemId = '$itemId'
");
I don't know what $dbCon is (Doctrine DBAL? mysqli?) so I can't tell you how to use query's result.
Wy don't you just count it,
$result = $dbCon->query("SELECT COUNT(itemId) FROM CVCinStoreCoins WHERE itemId = $itemId");
if $result > 0
I'm developing in php/sql a web application where users will be able to post items that they'd like to sell ( kinda like ebay ). I want non-members to be able to comment on the items or ask queries about items.
My problem is I want to display each item as well as any comment/query made about that item, in a similar manner as the way Facebook wall works.
I want to "append comments"(if any) to each item. The comments table is linked to the items table via column item_id. And the items table is linked to users table via column user_id. I have left joined users table with items table to display item details, i tried to left join comments table as well so that there are 3 joined tables.
That fails because no comments are displayed and only one item is displayed, despite there being multiple entries in each table. Here is the code i,m using.
$database->query
('
SELECT sale.*, query.*, users.id AS userid, users.username as user
FROM sale
LEFT JOIN users ON sale.user_id = users.id
LEFT JOIN query on sale.id = query.item_id
where category = "$category" ORDER BY sale.id DESC
');
$show = " "; //variable to hold items and comments
if ($database->count() == 0) {
// Show this message if there are no items
$show .= "<li class='noitems'>There are currently no items to display.</li>" ;
} else {
$show .= "<li>";
while ( $items = $database->statement->fetch(PDO::FETCH_ASSOC) )
{
$show .= "
//show item details in html
";
while( $query = $database->statement->fetch(PDO::FETCH_ASSOC) )
{
$show .= "
//show queries below item details
";
}
$show .= "</li>" ;
}
Welcome to Stackoverflow!
I recommend you taking a look at pdo. If you are already using mysql_ functions, then I recommend you switch. More on that can be found here.
Now that your pointed to the direction of to what functions to use when connecting/running queries, you now should create your tables. I use phpmyadmin for managing my database, I find it very good, but it's up to you what you use. Once you've decided on the service you use to manage your database, you should then learn how to use it by doing some google searches.
Now you need to set up your table and structure it correctly. If you say you're having items, then you should make a table called items. Next create the columns to the properties of the items. Also I recommend reading about Database Normalization, which is a key aspect of setting up your SQL tables Etc.
Once you have everything set up, you've connected to your database successfully Etc. You now need to set up the "Dynamic Page". What I mean by this is, there's only one page, say called 'dynamic', then a variable is passed to the url. These are called GET HTTP requests. Here's an example of what one would look like: http://example.com/item?id=345.
If you've noticed, you'll see the ? then the id variable defined to 345. You can GRAB this variable from the url by accessing the built in PHP array called $_GET[]. You can then type in your variable name you want to fetch into the []'s. Here's an example.
<?php
$data = $_GET['varname']; // get varname from the url
if(isnumeric($data)){ // is it totally made out of numbers?
$query = "SELECT fieldname FROM table WHERE id=:paramname";
$statement = $pdo->prepare($query); // prepare's the query
$statement->execute(array(
'paramname'=>$data // binds the parameter 'paramname' to the $data variable.
));
$result = $statement->fetch(PDO::FETCH_ASSOC); // grabs the result of the query
$result = $result['fieldname'];
echo 'varname was found in the database with the id equal to:'.$data.', and the result being: '.$result;
}
?>
So now you can see how you can grab the variable from the url and dynamically change the content with-in the page from that!
Hope this helped :)
I'm probably missing something obvious but when I try to execute this query, it returns no results. I plugged it directly into MySQL and also tried replacing the variable with a valid row value and I get the correct output. When I use a variable, it gives me no results. Anyone have any thoughs?
$query = "SELECT title FROM le7dm_pf_tasks WHERE project = (SELECT id FROM le7dm_pf_projects WHERE title = '".$ws_title."') ORDER BY title DESC LIMIT 1";
$result_query = mysql_query($query) or die("Error: ".mysql_error());
while ($row = mysql_fetch_assoc($result_query)) {
$result_title = $row['title'];
}
$result_title = substr($result_title,0,6);
echo $result_title;
Your SQL could do with some rework (though not the reason for your issue). No need for the nested select (which can also cause an error if it returns > 1 row). Try a join.
$sql = "
SELECT title FROM le7dm_pf_tasks t
INNER JOIN le7dm_pf_projects p ON t.project = p.id
WHERE p.title = '{$ws_title}'
ORDER BY title DESC LIMIT 1
";
You are also iterating over an unknown number of rows using the while statement. And then you exit and attempt a substring. How do you know that the last row iterated in the while had a value.
Try outputting $result_title inside the while loop itself to confirm data.
echo $result_title;
If you truly only have a single row, there is no need for the while loop. Just do
$row = mysql_fetch_assoc($result_query);
strip_tags($ws_title); - is what did it! The title was wrapped in an anchor tag that linked to that particular project page.
Thanks for all the good suggestions though. I'm gonna use some of them in the future when bug testing.
I am querying a large number of codes from my database, and need to have some validation before a user can input another code in to the database.
An example code would be this:
TD-BR-010212-xxxxxxxx
Where TD represents a promotion, BR represents a place, the numbers represent a date, and the rest are random.
My problem is that before the code is entered into the DB, I want to check to see if the date and place for that code already exists, as they should not be allwed to enter a code from the same place and date.
I assume it would be something within a loop as I already have:
$location_part_of_td = $code[2].$code[3];
$date_part_of_td = $code[4].$code[5].$code[6].$code[7].$code[8].$code[9];
$trade_day_result = mysql_query('SELECT * from wp_scloyalty WHERE promotion_type = trade-day') or die(mysql_error()); // Pulls all trade day codes from the database and checks the date part of the code.
// the date part exists with the same area part, user cant redeem.
while($info = mysql_fetch_array( $trade_day_result ))
{
$code = $info["product"];
}
But Im just not sure about the best way to check the strings..
You can use a MySQL LIKE clause to get entries in your DB that resemble your code.
Example:
$code_exists = mysql_query(
"SELECT 'a' FROM table_name WHERE column_name LIKE 'TD-BR-010212-%'"
);
if(mysql_num_rows($code_exists) > 0) {
// The specified place/date is taken
} else {
// No promotion at place BR on the specified date.
}
The '%' is used as a wildcard in SQL LIKE clauses.
You have two approach to solving this issue. Assuming you have access to alter the table.
Add a unique constraint to the table base off of the two columns.
Or Your approach by selecting all of the Location and Date, and see if it return any results.
SQL: SELECT COUNT(*) as counter FROM table where column = 'TD-BR-010212-%'
And check to see if counter return > 0;
I would use the LIKE statement in your SELECT and pull entries that start with the same promotion, place, and date. Unfortunately I don't know how your table looks so bear with me:
$promo_query = "SELECT * FROM wp_sclocalty WHERE column_name LIKE 'TD-BR-010212-%'";
$promo_result = mysql_query($promo_query);
if(mysql_num_rows($promo_result) == 0) {
// the promo code has NOT been used
} else {
// the promo code HAS been used
}
try this query
$part_code=substr($code, 0)
$records =mysql_query("select id from tableName where SUBSTRING(code,1,12)= $part_code");
if(mysql_num_rows($records) > 0)
{
// Duplicate exit
}
else
{
// insert code in DB
}
If you can, you'll get better performance and easier coding if you break apart the code into different fields when you save the data in each row. That way you can write queries that specifically check values for the components pieces of the code - you can even set rules in the database (like UNIQUE) to ensure that some parts are kept unique.
Specifically, I'd suggest:
create table your_table (
[... your other columns ...]
promotion char(2),
place char(2),
pr_date date,
pr_ident varchar(50)
)
Your first row would be ([...], 'TD','BR','2012-01-02', 'xxxxxxxx'). And queries would not require unpacking the formatted string - you could say things like "where promotion = 'TD' and place in ('BR','XX') ...". Simple, eh?