how to check if a table exist using pdo [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
MySQL check if a table exists without throwing an exception
Basically I have my MySQL dbname = test and my table name = page.
I want to create a query using a php PDO to check if the table "page" exists in my db "test"
I've tried this but it doenst work.. it always tells me that it doesnt exists.. even when it does
if (array_search('pages',$db->query('show tables')->fetch()) !== false) { echo "the db exists";
} else { echo "the db doesnt exists";
// Create tableS
//$IDB->execute();
}

there is no predefined test for existing table in PDO, you must do :
$pdo = new PDO($dsn,$user,$pass,$options);
$results = $pdo->query('SHOW TABLE LIKE \'page\'');
if(count($results)>0){echo 'table exists';}

Related

Displaying items in dynamic URL page in php from SQL database [duplicate]

This question already has answers here:
How to print a MySQL database table in PHP using PDO [closed]
(2 answers)
How can I get an unknown username given an ID?
(2 answers)
Closed 2 years ago.
I have made dynamic links in PHP, to display individual bikes, using the bike ID in my website. This is my code that makes each link individual on my index page:
$bike_id = $bike["bike_id"];
echo '<a href="./item.php?id='.$bike_id.'"><input type="button" value="See More" />';
Now the issue I face is trying to display each bike item pages unique values.
for example, if you selected "Fast bike" on index.php, you'd be taken to a page that had "fast bikes" description and price.
In the database, I have the columns:
"Bike_name",
"Bike_Price",
"Bike_Description
and on each the bikes item page, I want to display these values, but I don't know how to do it.
Here is what I have so far but it's not working:
<?php
require_once(__DIR__.'/includes/db.php'); //connect to the database
$item_id = $_GET['id']; //get the ID of the item
$item_data = mysql_query("SELECT bike_name"); //get the value of the column bike_name
echo "<h2>".$item_data['bike_name']."</h2>"; //display the value of the column bike_name
?>
I was advsed to do this:
// Select item from database
// Store results in $item_data
// echo $item_data[`item_name`];
My connection (I'm not showing my passwords or usernmane)
try {
$Conn = new PDO("mysql:host=".$db_config['db_host'].";dbname=".$db_config['db_name'],$db_config['db_user'],$db_config['db_pass']);
$Conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$Conn->setAttribute(PDO::ATTR_PERSISTENT, true);
$Conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch (PDOException $e) {
echo $e->getMessage();
exit();
}

Delete row(s) with respect to username [duplicate]

This question already has answers here:
delete using where and or
(4 answers)
Closed 4 years ago.
i've gone through most of the questions similar to this but none addressed my problem.
i have table with four columns : id,username,title and date. i want to delete the entire row(s) associated with a specific username when the user clicks a button (anchor tag). pls, how do i achieve this? heres the code i tried.
php
<?php
session_start();
$uname = $_SESSION['username'];
$dbconn = mysqli_connect('localhost','root','','notesdb');
if(!$dbconn){
die("Connection failed:". mysqli_connect_error($dbconn));
}
if($stmt = $dbconn->prepare("DELETE * FROM notes_log where username = ? ")){
$stmt->bind_param("s",$uname);
$stmt->execute();
$stmt->close();
}else{
echo "ERROR: could not prepare SQL statement.";
}
mysqli_close();
// redirect user after delete is successful
header("Location: index.php");
?>
HTML
Delete all
The above code redirected the page but nothing was deleted.
Get rid of the * in the query. The syntax is just:
DELETE FROM notes_log where username = ?
See DELETE Syntax.
In a multi-table DELETE you need to put the table names after DELETE, but a single-table DELETE should have nothing there.
And when an SQL operation fails, you should print the SQL error message, not just could not prepare SQL statement, e.g.
echo "ERROR: could not prepare SQL statement: " . $dbconn->error;
Edit: mysqli_close() requires a database connection as its only argument.
Ref: http://php.net/manual/en/mysqli.close.php
You will need to use mysqli_close($dbconn).

mysqli_query() generating query error [duplicate]

This question already has answers here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
I am trying to store form data into database using mysqli but it is generating query error my code is given below....
When ever I try to submit the database connection is generating.. the $_POST is working perfectly.. the error only generating by mysqli_query..
<?php
$name = $_POST["firstname"] . " " . $_POST["lastname"];
$email = $_POST["email"];
$happen = $_POST["whendidhappen"];
$howlong = $_POST["howlong"];
$howmany = $_POST["howmany"];
$describe = $_POST["describe"];
$whattheydid= $_POST["whattheydid"];
$seenmycat = $_POST["seenmycat"];
$anythingelse = $_POST["anythingelse"];
$dbc = mysqli_connect('localhost','root','','abductionreport')
or die('Database connection error');
$query = "INSERT INTO abductionform (firstname, lastname, email,whendidhappen, howlong, describe, whattheydid, seenmycat,anythingelse)VALUES('$name','$name','$email','$happen','$howlong', '$howmany','$describe','$whattheydid', '$seenmycat','$anythingelse')";
$result = mysqli_query($dbc,$query) or die ("Query Error");
mysqli_close($dbc);
?>
<h3>Aliens Abducted Me - Report an Abduction</h3>
<p>Thanks for Submiting the form.</p>
<?php
echo "$name it happend to you on $happen it take $howlong <br>";
echo "Number of aliens: $howmany<br>";
echo "Describe: $describe<br>";
echo "What they did to you: $whattheydid<br>";
echo "Have you seen my cat: $seenmycat<br>";
echo "Anything else : $anythingelse<br>";
echo "Your Email Address is : $email<br>";
?>
DESCRIBE is a mysql keyword. Wrap the column name in backticks. For that matter wrap your table and all columns in backticks. Always check that $_POST elements exist with isset () before trying to access them. Use mysqli prepared statements with placeholders for improved security. Always perform error checking BEFORE posting to SO.
You also have 9 columns and 10 values in your query - this will cause a failure every time.

PHP MySQL Update Query Failing [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 6 years ago.
I'm trying to execute the following query to update a record in a table.
require "conn.php";
$user_name = $_POST["username"];
$code = $_POST["code"];
$name = $_POST["groupname"];
echo "$user_name, $code, $name";
$sql_update = "UPDATE users SET group = '$name' WHERE username = '$user_name'";
if ($conn->query($sql_update) === TRUE) {
echo "success";
}
else {
echo "fail";
}
The query fails and I'm not sure why. The connection is made and I'm able to echo the username code and name. Is there a reason why it's not working?
Your code is not secure
Look at this code with prepared statements
require_once("conn.php");
$user_name = $conn->real_escape_string($_POST["username"]);
$code = $conn->real_escape_string($_POST["code"]);
$name = $conn->real_escape_string($_POST["groupname"]);
$sql_update = $conn->prepare("update `users` set `group` = ? where `username` = ?");
$sql_update->bind_param("ss",$name,$user_name);
$sql_update->execute();
$sql_update->close();
$conn->close();
And conn.php file should be like this
$config = parse_ini_file('config.ini'); // Connection infos.
$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['db_name']);
if($conn === false) {
die("Something was wrong ! Please try again later."); // Error if connection not ok.
}
$conn->set_charset("utf8");
Create file outside the public_html folder named config.ini to write connection data
[db_connection]
username = username
password = password
db_name = dbname
This function binds the parameters to the SQL query and tells the database what the parameters are. The "sss" argument lists the types of data that the parameters are. The s character tells mysql that the parameter is a string.
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
Learn more here

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

Categories