MySQL PHP Query placed within another query's while loop failing - php

I have a column of pony names, where the breeder's Prefix is included with the pony's name (eg. Ashbrook Boy, where Ashbrook is the Breeder's Prefix, and Boy is the name of the pony). I have another table where I have a list of all the Prefixes used. I want to cycle through that list, and for each record search through my ponies and fetch those whose names begin with each prefix in turn. When they are fetched, I want to remove the said prefix from their name, and pop it into a column for that purpose on their own table.
In the end, I want -rather than one column with both Prefix and Name mixed in - two columns: one for Prefix, one for Name.
I thought the code below would do it for me, but it's not working. I get a 'not a valid resource' error for $res. Any help you could give me would be hugely appreciated - I really don't want to do this by hand! :P
I'm using a PHP script off a MySQL db, which I can access via PHPMyAdmin.
include '../conn.php';
$q=mysql_query("SELECT DISTINCT Pre FROM prefixes");
while($r=mysql_fetch_array($q)) {
$pre=$r['Pre'];
$sql="SELECT ID, Name FROM profiles WHERE (Name REGEXP '^$pre') ORDER BY ID ASC";
mysql_query($sql);
echo $sql;
while($res=mysql_fetch_array($sql)){
$name=$res['Name'];
$name=trim(str_replace("$pre","", $name));
$id=$res['ID'];
mysql_query("UPDATE profiles SET Prefix = '$pre', Name = '$name' WHERE ID = '$id' ");
}
}
mysql_close($con);

Your mistake come from the fact that $sql is the query string, not the mysql result of the query
$sql="SELECT ID, Name FROM profiles WHERE (Name REGEXP '^$pre') ORDER BY ID ASC";
mysql_query($sql);
echo $sql;
while($res=mysql_fetch_array($sql)){
with this, it will look better :
$sql="SELECT ID, Name FROM profiles WHERE (Name REGEXP '^$pre') ORDER BY ID ASC";
$result = mysql_query($sql);
while($res=mysql_fetch_array($result)){

Related

How to order a MySQL query by last word of string with PHP PDO?

I have a column in my database table called "name" and it stores the users names as "FirstName LastName". I want the query to return the members ordered alphabetically by their last names.
$sql = 'SELECT * FROM members ORDER BY name';
$stmt = $pdo->prepare($sql);
$stmt->execute();
$members = $stmt->fetchAll(PDO::FETCH_ASSOC);
This doesn't work since the result is ordered by the whole name field and not the last name only. How could I fix this?
Thank you.
You may order using SUBSTRING_INDEX:
SELECT *
FROM members
ORDER BY SUBSTRING_INDEX(name, ' ', -1);
By the way, it is generally bad table design to store the first and last name in the same column. It would be much better to have two separate columns for the first and last names.

How to echo from MySQL the row that contain a city but also the row that are empty in the same field?

In my code I make use of this query. I want to include in the presentation the rows that have London in the pou field, and also the rows that the user have not selected any town and are empty.
$sql = "SELECT * FROM table WHERE eidos='online' AND pou='London' order by time asc";
I tried to add OR pou='' without luck. How can I do this?
Try
$sql = "SELECT * FROM table WHERE eidos='online' AND (pou='London' OR pou='') order by time asc";

SQL "LIKE" If empty returns all rows

Hello I have 2 textboxes and i want to give to the user the option to choose one in order to find results. The user can search through the id or the name. My problem is because i use LIKE%field% when the user chooses to search through the id the name field stays empty and returns all the table rows. I want to have results only if the user enters some value in the textbox. This is my sql query. I'm using mysql
"SELECT * FROM properties WHERE ID='$id' OR Name LIKE '%$name%'"
Thank you all
If the user has to select which field to search, you can do:
if ($_POST['search'] == 'id') {
$sql = "SELECT * FROM properties WHERE ID='$id'"
} else {
$sql = "SELECT * FROM properties WHERE Name LIKE '%$name%'"
}
You can do this in a single query (values are checked from the query itself):
"SELECT * FROM properties WHERE ('$id'='' OR ID='$id') AND ('$name' ='' OR Name LIKE '%$name%')"
Explanation:
First condition:
The query will select records with ID='$id' only when $id is not empty.
If $id is empty, query will not go for the second part ID='$id'
Second condition:
The query filters records with Name LIKE '%$name%' only when $name is not empty.
If $name is empty, query will not go for Name LIKE '%$name%'.
NB: This technique is extremely useful when you have numerous parameters to check, rather than using a bunch of if...elses at php side.

Show data from a specific row in MySQL

I'm building a simple bug tracking tool.
When you create a new project, all the info you fill in in the form, gets stored in the database.
When you create the new project you get redirected to a unique project page.
On top of the page it shows the name of the project, but it's not the name of the project I just created, it always shows the name of the first project in the MySQL table.
How can I show the name of the project I just created?
With this query I retrieve the data from the database.
$query = "SELECT CONCAT(name)
AS name FROM projects";
$result = #mysql_query ($query)
With this I show the project name, but it always shows the name of the first record in the table.
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
It isn't yet SQL Injection prove and is far from complete... But I'm really struggling with this problem.
You need an AUTO_INCREMENT field on your table for a unique identifier (at least, you really should). Then you can do something like this:
<?php
$sql = new MySQLi('localhost', 'root', '', 'database');
$sql->query('INSERT INTO `projects` (`name`) VALUES ("Test Project");');
$projectID = $sql->insert_id; // Returns the auto_increment field value of the last insert query performed
// So this assumes you have a field in your table called "id" in this example
$res = $sql->query('SELECT CONCAT(`name`) AS `name` FROM `projects` WHERE `id` = '.$projectID.';');
if ($row = $res->fetch_assoc()) {
echo '<h5>'.$row['name'].'</h5>';
}
?>
Since you were calling for a redirect to the unique project page, you should have something like this: header("Location: project.php?id=$projectID");
Then, on project.php, you can attempt to fetch the project with the query above, only your query's WHERE clause should be something like:
'`id` = '.intval($_GET['id']).';'
Technically, you could pass all the project info along to the next page as a request or a session cookie and save yourself a query altogether. Just make sure you keep the id handy so it's easy to update the record.
Try using ORDER BY.
$query = "SELECT CONCAT(name)
AS name FROM projects ORDER BY id DESC";
This would show the most recent project (assuming you have an ID column).
However, a much better way is to have an ID variable on the page.
$query = "SELECT CONCAT(name)
AS name FROM projects WHERE id=?";

PHP SQL Select From Where

I am having some difficulty running some SQL code.
What I am trying to do is, find a row that contains the correct username, and then get a value from that correct row.
This is my SQL in the php:
mysql_query("SELECT * FROM users WHERE joined='$username' GET name")
As you can see, it looks for a username in users and then once found, it must GET a value from the correct row.
How do I do that?
You need some additional PHP code (a call to mysql_fetch_array) to process the result resource returned by MySQL.
$result = mysql_query("SELECT name FROM users WHERE joined='$username'");
$row = mysql_fetch_array($result);
echo $row['name'];
mysql_query("SELECT `name` FROM users WHERE joined='$username' ")
Just select the right column in your 'select clause' like above.
Edit: If you are just starting out though, you might want to follow a tutorial like this one which should take you through a nice step by step (and more importantly up to date functions) that will get you started.
mysql_query("SELECT name FROM users WHERE joined='$username'")
$q = mysql_query("SELECT * FROM users WHERE joined='$username'");
$r = mysql_fetch_array($q);
$name = $r['user_name']; // replace user_name with the column name of your table
mysql_query("SELECT name FROM users WHERE joined='$username' ")
Read documentation : http://dev.mysql.com/doc/refman/5.0/en/select.html

Categories