mySQL search not really working - php

Here is a mySQL query with the password and usernames deliberately botched out. It is returning only one result is not returning any other information than today's date for that one result. It does not matter what search one tries it is not functioning.
<?php
$proto = $_GET['p'];
$terms = $_GET['f'];
$return;
if($proto == 'inline'){
echo 'checking';
$username="*******";
$password="*******";
$database="*******";
$my_text = $_GET['f']; //what I'm searching for
$my_category = '8'; //whatever category number it is
mysql_connect(localhost,$username,$password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
$result = mysql_query("SELECT ID FROM wp_posts WHERE post_title LIKE '%$my_text%' ");
// select all posts that have your text
while ($row = mysql_fetch_array($result));
$postname = $row['post_name'];
$posttitle = $row['post_title'];
$postID = $row['ID'];
$date = date ( 'd-M-Y' , strtotime($row['post_date']) );
$return.= '
'.$posttitle.' ('.$postname.')<br /><span style="font-size:10px; color:#555;">'.get_the_time("d-M-Y", $postID).' - '.get_post_meta($postID, "status", true).'</span>
';
//while have posts
echo $return;
}
?>

In addition to the other information:
I might be missing it, but I don't see you encompassing anything in your while loop.
That would be why it's only getting one. You need to use braces { }

Your query does not select post_name, post_title, or post_date. You said SELECT ID FROM wp_posts, so it selected ID and nothing else, as instructed. Your date() call sort of works because strtotime() is returning false, so it uses today's date as a fallback.

This:
mysql_query("SELECT ID FROM wp_posts WHERE post_title LIKE '%$my_text%' ");
is very unsafe - my_text isn't escaped, and is taken from GET params, so it opens you to a SQL Injection attack. Escape it using mysql_real_escape_string, or, better yet, use parametrized queries in your code.

Related

I have a column in a table that I would like to add up and display the result in a textbox. But its not working

I have a column in a table that I would like to add up and display the result in a textbox. But its not working.
<?php
function getpoint(){
$query = "SELECT sum(monthly_point) FROM characters WHERE
inmate_id = '$value'";
$result_set = mysql_query($query);
$row = mysql_fetch_array($result_set);
echo 'sum:'. $row[0];
}
?>
Switch to mysqli instead of mysql functions (out of date and not as secure) and parameterized statements. Your code is susceptible to SQL injection.
Two problems in your code. Add an alias to the sum column, and reference the column in the echo statement:
<?php
function getpoint() {
$query = "SELECT sum(`monthly_point`) as `sum` FROM characters WHERE inmate_id = '$value'";
$result_set = mysql_query($query);
$row = mysql_fetch_array($result_set);
echo 'sum:'. $row[0]['sum'];
}
?>
When you use var_dump() to display $row then it's OK ?
Please look it and add parameter as below
echo 'sum:'. $row['xxxxx'];
'xxxxx' : parameter

Selecting Mysql Meta_Value in Wordpress

Why the result return is null? What is wrong? If I use this consult on directly phpmyadmin, the result is correctly.
<?php $postid = get_the_ID(); ?>
<?php
$get_thumb = $wpdb->get_var
( "SELECT meta_value FROM `wp_postmeta` WHERE `post_id` = $postid AND `meta_key` = '_wp_attached_file'" );
echo "<p>Thumb URL: {$get_thumb}</p>";
?>
I'd suggest using the $wpdb->prepare() statement to ensure the SQL query is generated correct and the $get_thumb variable is correctly set in the query.
$postid = get_the_ID();
$get_thumb = $wpdb->get_var($wpdb->prepare(
"SELECT meta_value FROM `wp_postmeta` WHERE `post_id` = %s AND `meta_key` = '_wp_attached_file'",$postid));
echo "<p>Thumb URL: {$get_thumb}</p>";
Again you can always log the SQL string generated by prepare() to ensure it matches your expectations. See https://codex.wordpress.org/Class_Reference/wpdb#Examples for more examples.
I think your syntax has some trouble, so here's your original query revised.
<?php
$get_thumb = $wpdb->get_var(
"
SELECT meta_value
FROM wp_postmeta
WHERE post_id = " . $postid . " AND meta_key = _wp_attached_file
"
);
echo "<p>Thumb URL: {$get_thumb}</p>";
?>
I made sure the PHP is echoing correctly inside the query - I am not sure if that's a problem you were having.
I do recommend the prepared query too. Here is it with what I think is correct syntax (I found it was helpful to prepare items by putting them in a $query_arg_array). See https://codex.wordpress.org/Class_Reference/wpdb.
$postid = get_the_ID();
$query_arg_array = [$postid];
$get_thumb = $wpdb->get_var($wpdb->prepare(
"
SELECT meta_value
FROM wp_postmeta
WHERE post_id = %d AND meta_key = _wp_attached_file
",
$query_arg_array
));
echo "<p>Thumb URL: {$get_thumb}</p>";
If that prepared query didn't work, try putting $postid directly as argument instead of the $query_arg_array.
Remember SQL is super sensitive so even an extra space can throw off your query.

MySQL query to select SUM of longtext data type and store result as variable

I need to select some values from a table column which has a datatype of "longtext" where another column has a specific value and add those values up. I need to store the sum as a variable which I will a.) echo on a webpage, and b.) use the value in a calculation later in the page.
This works to find all of the values which I need to add up:
$query = "SELECT meta_value
FROM wp_postmeta
WHERE meta_key = '_crowdfundingtotalprice'
ORDER BY CAST(`meta_value` AS UNSIGNED) DESC";
and I can display the results with:
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo $row['meta_value']. "<br>";
}
From my searching, I think I am close with my query, but my page fails to load when I try to echo the results. Here is what doesn't work:
$query = "SELECT CAST(SUM('meta_value') as UNSIGNED)
FROM wp_postmeta
WHERE meta_key = '_crowdfundingtotalprice'";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo $row[SUM('meta_value')]. "<br>";
}
As you may have guessed, this is a Wordpress database table, and I cannot change the datatype. As always, your help is appreciated!
EDIT - Trying Gordon Linoff's suggestion below, I have removed the single quotes around meta_value. It still doesn't work, but thank you for the suggestion:
$query = "SELECT CAST(SUM(meta_value) as UNSIGNED)
FROM wp_postmeta
WHERE meta_key = '_crowdfundingtotalprice'";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo $row[SUM(meta_value)]. "<br>";
}
SOLVED:
Thank you to Gordon Linoff for pointing out my typographical error. I ended up making a sample table and hammering this out on my own. Indeed, the single quotes in my query were not needed. However, where I was echoing the results, I needed the single quotes, but they were in the wrong place. Note $row['SUM(meta_value)'] instead of $row[SUM('meta_value')].
Additionally, I did not need to use CAST (which didn't work), because MYSQL will by default treat values as mathematical values if the query uses math.
$query = "SELECT meta_key, SUM(meta_value)
FROM wp_postmeta
WHERE meta_key = '_crowdfundingtotalprice'";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo $row['SUM(meta_value)'] ."<br>";
}

How WHERE clause works when inserting php variables

I am having problems trying to get these queries with a WHERE clause to work. I have two tables which look like this :
What I am trying to do is return the genre that each film has. At the moment no data is returning at all from what I can see. Here are the two queries:
$film_id = $row_movie_list['film_id'];
mysql_select_db($database_fot , $fot);
$query_get_genre = "SELECT * FROM film_genre WHERE `id_film` ='". $film_id. "'";
$get_genre = mysql_query($query_get_genre, $fot) or die(mysql_error());
$row_get_genre = mysql_fetch_assoc($get_genre);
$totalRows_get_genre = mysql_num_rows($get_genre);
$genre_id = $row_get_genre['id_genre'];
mysql_select_db($database_fot , $fot);
$query_genre = "SELECT * FROM genre WHERE `id_genre` ='". $genre_id. "'";
$genre= mysql_query($query_genre, $fot) or die(mysql_error());
$row__genre = mysql_fetch_assoc($genre);
$totalRows_genre = mysql_num_rows($genre);
PHP with content area. I fairly new to PHP so any help would be appreciated.
<?php do { echo $genre['genre']; } while($row_get_genre = mysql_fetch_assoc($get_genre)); ?>
Update: I am now able to get first genre but not second it just echos the first one twice and I have tried but still no luck:
do {do { echo $row_genre['genre']; } while($row_genre = mysql_fetch_assoc($genre));} while($row_get_genre = mysql_fetch_assoc($get_genre)); ?>
Avoiding the fact that you're using a deprecated way to establish connection and interact with MySQL, what you're doing is getting a single relation genre-film and then getting the row of the genre that matches. You should surround part of your code with a while that executes while it's still genres of the film with id. Something like:
$film_id = $row_movie_list['film_id'];
mysql_select_db($database_fot , $fot);
$query_get_genre = "SELECT * FROM film_genre WHERE `id_film` ='". $film_id. "'";
$get_genre = mysql_query($query_get_genre, $fot) or die(mysql_error());
while($row_get_genre = mysql_fetch_assoc($get_genre)){
$genre_id = $row_get_genre['id_genre'];
$query_genre = "SELECT * FROM genre WHERE `id_genre` ='". $genre_id. "'";
$genre= mysql_query($query_genre, $fot) or die(mysql_error());
$row__genre = mysql_fetch_assoc($genre);
// You should do whatever you want to do with $row__genre here. Otherwise it will be cleared.
}
I must insist this is a deprecated and insecure way of communication with a MySQL Database. I recommend you read about MySQLi or PDO extensions.
MySQLi: http://www.php.net/manual/en/book.mysqli.php
PDO: http://www.php.net/manual/en/book.pdo.php

Simple way to read single record from MySQL

What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)

Categories