I have this query I can run against my db and it works fine. However when I try it in the PHP version I get 0 results. I'm missing something fundamental, I just can't tell what it is.
Query
SELECT *
FROM table_admin_20
WHERE column1 = '0607'
PHP
$store_info_query = "SELECT * FROM '".$table_name."' WHERE 'column1' = '".$store_number."'";
if ($query_run = mysql_query($store_info_query)) {
if (mysql_num_rows($query_run) == NULL) {
$response["success"] = 0;
echo json_encode($response);
echo 'nope';
} else {
while ($row = mysql_fetch_assoc($query_run)) {
$store_info = $row['column1'];
echo '1111111';
echo $store_info;
}
}
} else {
echo 'fail';
}
I know I have 0 protection against SQL injection, I'm merely trying to pull data, this is in no way live yet. Anyways, I get the 'fail' response each time. Thanks for any help.
Don't add security as an afterthought, just switch to PDO or mysqli and use prepared statements so that you don't have to worry about the values any more. In case of table- or column names, you would need to use white-lists though.
The cause of your problem is that you are quoting your table- and field names. If you need to escape them, use backticks:
$store_info_query = "SELECT * FROM `".$table_name."` WHERE `column1` = '".$store_number."'";
You've to replace ' with ` for the table and column names. ' is just for values. Try this:
$store_info_query = "SELECT * FROM `".$table_name."` WHERE `column1` = '".$store_number."'";
Please avoid using * and rethink your security-strategies. As already mentioned, take a look at PDO: http://php.net/manual/en/book.pdo.php
You are putting wrong quotes around table name and column name. Try this
$store_info_query = "SELECT * FROM `".$table_name."` WHERE `column1` = '".$store_number."'";
Related
I try querying very simple sql statement with mysqli
"select * from area where area_pre_id=6035;"
it returns nothing.
After querying this in phpmyadmin , it returns 78 rows ....
PHP code is as below;
$sql = "select * from area where area_pre_id=6035;";
if ($result = mysqli_query($conn, $sql, MYSQLI_USE_RESULT)) {
while($obj = $result->fetch_object()){
if($obj->area_local_name_th){
$my_province = $obj->area_local_name_th . "(" . $obj->area_eng_name . ")";
}else{
$my_province = $obj->area_eng_name;
}
$line[] = array("ProvinceID"=>$obj->area_id,"ProvinceName"=>$my_province);
}
}
Please tell me what's wrong with my code or sql statement.
Your mysqli command is right.I think there is no value in your database for that particular id.
Is the datatype of that id fild integer?
If it is integer then the query is right.But if it is varchar then you have to put a single quote.
select * from area where area_pre_id='6035';
You are trying to use both procedural and OOPs concept. THat will be the issue.
Try this
Change $result->fetch_object() to mysqli_fetch_object($result)
I have a php code with a query:
$query = "SELECT * FROM TDdb WHERE status = $status AND occupation =$occupation";
I am sending the values status and occupation with a client application to this php code.
This works when I send both status and occupation. But I want it to return rows if I just send status but not occupation also ( I mean no matter what the occupation is).
does anyone have any suggestions?
I would appreciate any help.
PS: I want to do it without if statement and just but changing the query
Personally I would create a base query and append conditions wherever you have them, like so:
$sql = 'SELECT * FROM TDdb';
$conditions = array();
$args = array();
if ($action) {
$conditions[] = 'status = :status';
$args[':status'] = $status;
}
if ($occupation) {
$conditions[] = 'occupation = :occupation';
$args[':occupation'] = $occupation;
}
if ($conditions) {
$sql .= ' WHERE ' . join(' AND ', $conditions);
}
$stmt = $db->prepare($sql);
$stmt->execute($args);
Looks like you've got a few good options for how to do it in SQL, or how to make the SQL string variable in PHP.
One reason to consider using an 'if' in the PHP code for the database access performance.
When you introduce an 'or' condition like that in SQL, you're not going to get index access. It is much harder for the database to determine what path it should take than for the PHP code because the SQL engine optimizes the query without knowing what the variable will resolve to at execution.
You already know in the PHP which version of the query you really want. This will perform better if you make that choice there.
This will work if you pass an occupation or a NULL value.
SELECT *
FROM TDdb
WHERE status = $status
AND ($occupation IS NULL OR occupation = $occupation)
"SELECT * FROM TDdb WHERE status = '$status' AND (occupation = '$occupation' OR occupation IS NULL)";
Apart from the solution provided by #Tom and #Damien Legros, you may create two query strings one with occupation and one without occupation. Something like:
$query = "SELECT * FROM TDdb WHERE status = $status";
if ($occupation != "") {
/*When you have value for occupation*/
$query .= " AND occupation =$occupation";
}
So in this case, data will be returned if you have only the status field. Secondly, please check if the status and occupation fields in table are varchar then you have to enclose them in single quotes (').
Thanks everyone for help. specially jack.
finally i created my query like this:
$query = 'SELECT * FROM TDdb';
if ($status) {
$query = $query." WHERE status = '".$status."'";
}
if ($occupation) {
$query = $query." AND occupation = '".$occupation."'";
}
I think this should work but it is not...
Basically i am trying to check mysql db to see if there is a record that meets the 2 variables..if no do one thing if yes do another thing. the result is always no at this point.
$result = mysql_query("SELECT 'lastname' FROM 'Cust_Releases' WHERE 'lastname' = '$usercheck' AND 'TripID'= '$RLtripid'");
echo $result;
if(mysql_num_rows($result) == 0) {
echo"no";// row not found, do stuff...
}
else {
echo"yes"; // do other stuff...
}
First of all, stop using mysql_* functions because this extension is deprecated as of PHP 5.5.0.
Second always use the (`) symbol around database names, table names and column names.
You have a reserved word used RELEASE.
$sql = "SELECT `lastname` FROM `Releases` WHERE `lastname` = '$usercheck' AND `TripID` = '$RLtripid'";
Reserved words you find here
$result = mysql_query("SELECT lastname FROM `Releases` WHERE lastname = '$usercheck' AND TripID= '$RLtripid' LIMIT 1");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
echo $result;
if(mysql_num_rows($result) == 0) {
echo"no";// row not found, do stuff...
}
else {
echo"yes"; // do other stuff...
}
Escaping 'Releases', as Bondye suggested
Adding 'LIMIT 1' to your query to allow the possibility of an early-out when there is more than one matching record. You don't appear to need the total count. May not make any difference if unique constraints exist which guarantee that only one row can be returned
mysql_query is deprecated. In real code you should be using PDO and prepared statements / bind variables!
debugging is a very important thing in programming. first do make sure that the varibales $usercheck, and $RLtripid contain values.
-----------------------
$sql = "SELECT `lastname` FROM `Cust_Releases` WHERE `lastname` = '$usercheck' AND `TripID`= '$RLtripid'";
echo $sql;
$result = mysql_query($sql);
....-------------------
Try this code. It will help you
$result = mysql_query("SELECT COUNT( * ) from Cust_Releases lastname = '$usercheck' AND TripID= '$RLtripid'");
if($result == 0) {
echo"no";// row not found, do stuff...
}
else {
echo"yes"; // do other stuff...
}
My code is here :
$array_letter = array("A","B","C","Ç","D","E","F","G","H","I","İ","J","K","L",
"M","N","O","P","R","S","Ş","T","U","Ü","V","Y","Z");
$sql = "SELECT id,city FROM city WHERE city LIKE '" .$array_letter[$i]."%'";
And after these codes :
for ($i=0;$i<27;$i++) {
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<h3>".$row['city']."</h3>";
}
}
$sql is meaningless because $array_letter[$i]will not work there. But $sql must be top of these codes for design. Because I coded switch-case statement. According to requests, $sql will change for this reason I can not write $sql under for loops. But all my queries depens on $array_letter. How can I make $array_letter work?
You should use the mysqli driver and prepared statements:
$st = $mysqli->prepare("SELECT id,city FROM city WHERE city LIKE ?'");
for ($i=0;$i<27;$i++) {
$st->bind_param("s", $array_letter[$i].'%');
$st->execute();
$result = $st->get_result();
while ($row = $result->fetch_assoc()) {
echo "<h3>".$row['city']."</h3>";
}
}
Although for this case, I would recommend just doing one big query since it looks like you are getting everything: SELECT id,city FROM city ORDER BY city...
For educational purposes, an alternative approach would be to do something like:
$sql = "SELECT * FROM foo WHERE bar='%s'";
mysql_query(sprintf($sql, "42"));
That can be useful in other situations, but again, if you are writing SQL, use prepared statements as they solve this problem more gracefully with the extra protection of helping to prevent SQL injection attacks and minimizing the amount of SQL parsing the server has to do.
You should use prepared statements, as Matthew mentioned in his answer.
Otherwise consider this (using PHP 5.3 closures):
$sql = function($i) use ($array_letters) {
return "SELECT id,city FROM city WHERE city LIKE '" .$array_letter[$i]."%'";
}
Then inside your loop:
mysql_query($sql($i));
This will help to reduce the database calls.
$array_letter = array("A","B","C","Ç","D","E","F","G","H","I","İ","J","K","L",
"M","N","O","P","R","S","Ş","T","U","Ü","V","Y","Z");
for($i=0;$i<count($array_letter);$i++){
if($i!=count($array_letter)-1)
$qstring.="city like '".$array_letter[$i]."%' or ";
else
$qstring.="city like '".$array_letter[$i]."%'";
}
$sql = "SELECT id,city FROM city WHERE ".$qstring;
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<h3>".$row['city']."</h3>";
}
What is the best way to check if a table exists in MySQL (preferably via PDO in PHP) without throwing an exception. I do not feel like parsing the results of "SHOW TABLES LIKE" et cetera. There must be some sort of boolean query?
Querying the information_schema database using prepared statement looks like the most reliable and secure solution.
$sql = "SELECT 1 FROM information_schema.tables
WHERE table_schema = database() AND table_name = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$tableName]);
$exists = (bool)$stmt->fetchColumn();
If you're using MySQL 5.0 and later, you could try:
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '[database name]'
AND table_name = '[table name]';
Any results indicate the table exists.
From: http://www.electrictoolbox.com/check-if-mysql-table-exists/
Using mysqli I've created following function. Assuming you have an mysqli instance called $con.
function table_exist($con, $table){
$table = $con->real_escape_string($table);
$sql = "show tables like '".$table."'";
$res = $con->query($sql);
return ($res->num_rows > 0);
}
Hope it helps.
Warning: as sugested by #jcaron this function could be vulnerable to sqlinjection attacs, so make sure your $table var is clean or even better use parameterised queries.
This is posted simply if anyone comes looking for this question. Even though its been answered a bit. Some of the replies make it more complex than it needed to be.
For mysql* I used :
if (mysqli_num_rows(
mysqli_query(
$con,"SHOW TABLES LIKE '" . $table . "'")
) > 0
or die ("No table set")
){
In PDO I used:
if ($con->query(
"SHOW TABLES LIKE '" . $table . "'"
)->rowCount() > 0
or die("No table set")
){
With this I just push the else condition into or. And for my needs I only simply need die. Though you can set or to other things. Some might prefer the if/ else if/else. Which is then to remove or and then supply if/else if/else.
Here is the my solution that I prefer when using stored procedures. Custom mysql function for check the table exists in current database.
delimiter $$
CREATE FUNCTION TABLE_EXISTS(_table_name VARCHAR(45))
RETURNS BOOLEAN
DETERMINISTIC READS SQL DATA
BEGIN
DECLARE _exists TINYINT(1) DEFAULT 0;
SELECT COUNT(*) INTO _exists
FROM information_schema.tables
WHERE table_schema = DATABASE()
AND table_name = _table_name;
RETURN _exists;
END$$
SELECT TABLE_EXISTS('you_table_name') as _exists
As a "Show tables" might be slow on larger databases, I recommend using "DESCRIBE " and check if you get true/false as a result
$tableExists = mysqli_query("DESCRIBE `myTable`");
$q = "SHOW TABLES";
$res = mysql_query($q, $con);
if ($res)
while ( $row = mysql_fetch_array($res, MYSQL_ASSOC) )
{
foreach( $row as $key => $value )
{
if ( $value = BTABLE ) // BTABLE IS A DEFINED NAME OF TABLE
echo "exist";
else
echo "not exist";
}
}
Zend framework
public function verifyTablesExists($tablesName)
{
$db = $this->getDefaultAdapter();
$config_db = $db->getConfig();
$sql = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{$config_db['dbname']}' AND table_name = '{$tablesName}'";
$result = $db->fetchRow($sql);
return $result;
}
If the reason for wanting to do this is is conditional table creation, then 'CREATE TABLE IF NOT EXISTS' seems ideal for the job. Until I discovered this, I used the 'DESCRIBE' method above. More info here: MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050
Why you make it so hard to understand?
function table_exist($table){
$pTableExist = mysql_query("show tables like '".$table."'");
if ($rTableExist = mysql_fetch_array($pTableExist)) {
return "Yes";
}else{
return "No";
}
}