php mysql cant find id if there is letters inside [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
When i try to search for a available id with numbers, it echos correctly.
HOWEVER, if there is a single letter inside, like this: 5325252T, It wont find it in the database.
I have a column with type: longtext
How can I get around this? I never noticed this problem before and now I'm in a hurry to fix it...
Btw, If i echo all the tables for rusp_9_cf7dbplugin_submits, it also shows those ids with letters inside. Really weird.
// Create connection
$conn = new mysqli($hostname, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT field_value FROM rusp_9_cf7dbplugin_submits WHERE field_value = 5325252T"; // If i remove the T, It will find the id and echo it in a table, but if the T is there, it wont find the id at all...
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["field_value"]."</td><td>".$row["field_value"]." ".$row["field_value"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();

Just enclose the field_value value in single inverted commas ' since adding a character makes the SQL engine interpret that value as a number where as it is a string literal, whereas if its just numbers then it interprets it as an integer.
Your code becomes...
...
$sql = "SELECT field_value FROM rusp_9_cf7dbplugin_submits WHERE field_value = '5325252T'"; // If i remove the T, It will find the id and echo it in a table, but if the T is there, it wont find the id at all...
...

Related

Selecting * from table returns nothing

I wrote this php script that allows me to fetch all the rows in a table in my MySQL database.
I have put the echo "1", etc. to see whether it gets to the code at the very end. The output proves it does. However, it does not output anything when echoing json_encode($resultsArray), which I can't seem to figure out why.
Code:
// Create connection
$connection = mysqli_connect("localhost", "xxx", "xxx");
// Check connection
if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } else { echo "0"; }
// select database
if (!mysqli_select_db($connection, "myDB")) { die('Unable to connect to database. '. mysqli_connect_error()); } else { echo "1"; }
$sql = "select * from myTable";
$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));;
echo "3";
$resultsArray = array();
while($row = mysqli_fetch_assoc($result)) {
// convert to array
$resultsArray[] = $row;
}
echo "4";
// return array w/ contents
echo json_encode($resultsArray);
echo "5";
Output:
01345
I figured, it is not about the json_encode, because I can also try to echo sth. like $result['id'] inside the while loop and it just won't do anything.
For testing, I went into the database using Terminal. I can do select * from myTable without any issues.
Any idea?
After around 20hrs of debugging, I figured out the issue.
As I stated in my question, the code used to work a few hours before posting this question and then suddenly stopped working. #MichaelBerkowski confirmed that the code is functional.
I remembered that at some point, I altered my columns to have a default value of an empty string - I declared them as follows: columnName VARCHAR(50) NOT NULL DEFAULT ''.
I now found that replicating the table and leaving out the NOT NULL DEFAULT '' part makes json_encode() work again, so apparently there's an issue with that.
Thanks to everybody for trying anyway!

removing common words from php/mysql search program [duplicate]

This question already has answers here:
mysql keyword search
(2 answers)
MySQL Fulltext Stopwords Rationale
(1 answer)
Closed 5 years ago.
Ok so I'm pretty new to PHP and building a question/answer site. I want a page where the user can search my questions table to find a question and after some research and work I've come up with this but my problem is common words. If a user types "is" in the search every question with "is" in it turns up. My question is either 1) Is my approach to this search function completely wrong? or 2) is there a way I can inject an array of common words to be omitted from the query?
search_reslut.php:
<?php
$servername = "127.0.0.1";
$username = "dylan326";
$password = "";
$dbname = "questions87";
$port = 3306;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname, $port);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Your search results: <br>";
echo "<br />";
$query = $_POST['query'];
$query = "$query $query $query";
$pieces = explode(" ", $query);
$qindex0 = $pieces[0]; // piece1
$qindex1 = $pieces[1]; // piece2
$qindex2 = $pieces[2]; // piece3
$qindex3 = $pieces[3];
$qindex4 = $pieces[4];
$qindex5 = $pieces[5];
$qindex6 = $pieces[6];
echo $query;
$sql = "select q_id, question, username, q_date from questions where (question like '%$qindex0%' or question like '%$qindex1%' or question like '%$qindex2%' or question like '%$qindex3%'
or question like '%$qindex4%' or question like '%$qindex5%' or question like '%$qindex6%')";
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result)){
$question = $row['question'];
echo ('<a href="totalqs.php?q_id=' . $row['q_id'] .'" >' . $question .'Asked by:'.' '.$row['username'].' '.$row['q_date'] .' </a>' . '<br>');
}}
else {echo "No resluts found";}
?>
MySQL has the ability to make keyword searches easy and much faster than what you're doing. This is done through the MATCH(column) AGAINST ('words to search') syntax. Add a FULLTEXT index to your table, for the column you want to make searchable (question). Then something like this would work to return all questions that have at least one of the search words
// Get the query. escape all single quotes.
$words = str_replace("'","\'",$_POST['query']);
$sql = <<< "SQL"
select q_id, question, username, q_date from questions
where MATCH(`question`) AGAINST('$words' IN BOOLEAN MODE)
SQL;
$result = $conn->query($sql);
The nice thing about FULLTEXT searches is that they automatically exclude common words (stop words) from the searches for you. Learn more here as well as here
If you have a custom list of stop words, you can just remove them from the $words string before you execute the query
$stopWords = [
'/is/',
'/the/'
];
// Where is the cat >> Where cat
$words = preg_replace($stopWords,'',$words);
Note from the docs:
Full-text indexes can be used only with MyISAM tables. (In MySQL 5.6 and up, they can also be used with InnoDB tables.) Full-text indexes can be created only for CHAR, VARCHAR, or TEXT columns.

MySQLi how to check if table exists? [duplicate]

This question already has answers here:
MySQLi Table Exists
(5 answers)
Closed 3 years ago.
I want to create table by app if there's no such table. But doing it for the first time... Need some help, tho
//connecting...
$mysqli = new mysqli($db_params['host'], $db_params['login'], $db_params['pass'], $db_params['name']);
if ($mysqli->query("SHOW TABLES LIKE `products`")){
echo ' YES';
} else echo 'no';
It always says NO.
Read their documentation? https://dev.mysql.com/doc/refman/5.5/en/replication-features-create-if-not-exists.html Seems like you can do that easily:
CREATE TABLE IF NOT EXISTS `products`
This way you don't have to check first whether a table exists or not, you just create one if it doesn't.
And it seems like you have a syntax error, which is probably the reason why your code keeps returning "no". This should work:
SHOW TABLES LIKE 'products';
Just use single or double quotes, no backticks like `.
You use backticks (`) for table and column names, single (') or double quotes (") for strings, in this case you are giving a string so you should use single or double quotes.
In order to create a table if it not exists, you can use
CREATE TABLE IF NOT EXISTS
Use PHP DESCRIBE statement.
if(mysql_query("DESCRIBE `table_name`")) {
// Exists
}
This solution works for me JUST FINE:
<?php
// connect to the "tests" database
$conn = new mysqli('localhost', 'root', 'pass', 'tests');
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
// SQL query
$sql = "SHOW TABLES IN `tests`";
// perform the query and store the result
$result = $conn->query($sql);
// if the $result not False, and contains at least one row
if($result !== false) {
// if at least one table in result
if($result->num_rows > 0) {
// traverse the $result and output the name of the table(s)
while($row = $result->fetch_assoc()) {
echo '<br />'. $row['Tables_in_tests'];
}
}
else echo 'There is no table in "tests"';
}
else echo 'Unable to check the "tests", error - '. $conn->error;
$conn->close();
?>
For a complete and more examples, here the source : http://coursesweb.net/php-mysql/check-table-exists-database_t

Sql echo row with php [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I can connect to DB but i cant echo , all time that said 0 results but my DB have TABLE (text) with 2 COLUMN id and text and i have inserted text in my table.
$con = mysqli_connect("localhost","1078362","nenaddurmisi022");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT vesti FROM comment";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0)
{
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["vesti"]."<br>";
}
}
else {
echo "0 results";
}
mysqli_close($con);
You're using all mysqli functions except for your database connection. Try changing the first line to...
$con = mysqli_connect("localhost", "1078362", "nenaddurmisi022");
...and change the last line to...
mysqli_close($con);
I'm guessing there are a lot of errors generated by this script, but you're not seeing them. You should add these lines to the top of the script...
error_reporting(E_ALL);
ini_set('display_errors', 1);
try
$sql = "SELECT * FROM text";
instead of
$sql = "SELECT text FROM text";
also be sure you'r table name is text.
one last thing you could try is to replace
echo $row["text"]."<br>";
by
print_r($row);
to see if there's a result set from you'r Database

SQL insert not saving to database [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
Im having trouble getting this simple code to work, it,s part of a rating script for a product page.
$connn = new mysqli($servername, $username, $password, $dbname);
if ($connn->connect_error) {
die("Connection failed: " . $connn->connect_error);
}
$vresult1 = mysqli_query($connn,"SELECT * FROM rating_log WHERE ip=$userIP AND product_id=$pid");
if ($vresult1->num_rows > 0) {
// ERROR: user already voted
$v_msg = '<div style="color:red;">You have already voted on this product!</div>';
} else {
// enter vote
mysqli_query($connn,"UPDATE wc_products SET rating=$votecnt1");
mysqli_query($connn,"INSERT INTO rating_log (ip, product_id) VALUES ($userIP, $pid)");
$v_msg = '<div style="color:green;">Thank you for voting! DEBUG['.$userIP.'-'.$pid.']</div>';
}
$conn->close();
} // end rating
All this should do is add a new entry which logs a user ip and the id of the product, then update the product db to register the vote. The update works fine but it wont log the user.
Try this:
$userIP = $mysqli->real_escape_string($userIP);
$pid = $mysqli->real_escape_string($pid);
mysqli_query($connn,"INSERT INTO rating_log (ip, product_id) VALUES ('$userIP', '$pid')");
Single quotes should be used for string values like in the VALUES() list. for more details read this post answer:
When to use single quotes, double quotes, and backticks in MySQL

Categories