This question already has answers here:
How can I check if a MySQL table exists with PHP?
(12 answers)
Closed 7 years ago.
I'm trying to see if a table already exists and then act accordingly. I was unable to solve my problem from viewing previous posts.I'm aware of a secondary problem where the sql throws an error but I don't know why it throws. When I replace $thisTable with the actual string, it works. But my primary problem is not being able to detect if the table exists.
$thisTable = "testX";
$thisTable = preg_replace("/[^A-Z,a-z,0-9]/", '', $thisTable);
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SHOW TABLES LIKE ".$thisTable;
//I get an SQL error here?
$stmt = $conn->prepare($sql);
$stmt->execute();
$isThere = $stmt->num_rows;
if ($isThere > 0){
echo "Already exists."
} else {
echo "Doesn't exist."
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage() . "<br/>WITH QUERY: " . $sql;
}
You need quotes around the table name in the query.
$sql = "SHOW TABLES LIKE '$thisTable'";
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 2 years ago.
I want to query one new to sql table, the code run but it doesn't insert anything into the database.
I try to read back the pdo manual but doesn't understand which part I am wrong.
$query = "INSERT INTO 'easycomputing'('STID', 'NAME', 'TONG') VALUES (:STID, :NAME, :TONG)";
$dns = " mysql:host=localhost;dbname=phan1";
$username="root";
$password= "";
// $password="";
try{
//access the database
$db = new PDO($dns, $username, $password);
//execute the query
$statement = $db->prepare($query);
$statement->bindValue(':STID', 137, PDO::PARAM_INT);
$statement->bindValue(':NAME', 'tenten', PDO::PARAM_STR);
$statement->bindValue(':TONG', 5, PDO::PARAM_INT);
//execute the query
if( $statement->execute() ){
echo "record tranfer successfully";
}else{
echo "fail to execute the record";
}
Sorry, but I think that you shouldn't isert the name of columns between codes : (STID, NAME, TONG)
This question already has answers here:
Sql syntax error using UPDATE database query [closed]
(2 answers)
Closed 7 years ago.
I'm trying to Update Data in MySQL using PDO.
I have set up the code below but get the error
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in >your SQL syntax; check the manual that corresponds to your MySQL server version >for the right syntax to use near '(h1, text) values ('Blah blah' at line 1
if (isset($_POST['Submit']))://if admin wants to edit category
$h1 = $_POST['h1'];
$text = $_POST['text'];
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "dbname";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare statement
$stmt = $conn->prepare('UPDATE sections (h1, text) values (:h1, :text) WHERE id=1');
$stmt->bindParam(':h1', $h1);
$stmt->bindParam(':text', $text);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
Update syntax should be:
UPDATE table_name SET `field1` = new-value1, `field2` = new-value2.
Your query should be:
UPDATE sections SET `h1` = :h1, `text` = :text WHERE id = 1;
See the Update query syntax
text is a reserved word in mysql.
Write your query as below:-
UPDATE sections SET `h1` = :h1, `text` = :text WHERE id = 1;
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 a beginner with PHP and I'm stucked with a simple request that returns nothing.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM order";
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
echo "something";
}
$conn->close();
This table is not empty.
I'm clueless...
Your code looks alright.
To get errors that may have occured you can change the following:
$result = $conn->query($sql);
if(!$result) {
die($conn->error);
}
echo "Result rows: "+ $result->num_rows;
You might find an error this way.
This question already has answers here:
Reference — frequently asked questions about PDO
(3 answers)
Closed 8 years ago.
I have an update query
$query = $db->prepare("UPDATE user SET UserID='6',UserName='xyz' WHERE UserID= '6' ");
$query->execute();
it runs fine, but when I change field UserName to UserNamee
$query = $db->prepare("UPDATE user SET UserID='6',UserNamee='xyz' WHERE UserID= '6' ");
$query->execute();
It should show error, but it doesn't show any error
I just want to handle these kind of errors in my project.
you can track the error in PDO using errorCode() function this function returns 0000 when no error else return a 4 digit number (error code), for your example you can try :
$query = $db->prepare("UPDATE user SET UserID='6',UserNamee='xyz' WHERE UserID= '6' ");
$query->execute();
if($query->errorCode()=='0000')
{ echo 'no error'; }
else
{ echo 'error'; }
PDO has various error modes that you can pass to the constructor as the driver_options argument. You can find them at http://php.net/manual/en/pdo.setattribute.php . Most people use array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION).
You should use try-catch:
try {
$query = $db->prepare("UPDATE user SET UserID='6',UserName='xyz' WHERE UserID= '6' ");
$query->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
And remember to do this after connection at the database:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
$query = $db->prepare("UPDATE user SET UserID='6',UserNamee='xyz' WHERE UserID= '6' ");
if (!$query) {
print_r($db->errorInfo());
}
else
$query->execute();
I have a large database (28k entries in this particular table one table) and I need to append some HTML tags to the front and back of every column in a table.
Here is my code:
try
{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
if(!$conn)
{
echo "Error in connecting to the database.";
}
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$query = $conn->query("SELECT `id`, `introtext` FROM *TABLE* WHERE id >= 41155");
$query->setFetchMode(PDO::FETCH_OBJ);
//For each row in the table
while($row = $query->fetch())
{
$introtext = '<span class="*SPAN CLASS*">' . $row->introtext . '</span>';
$update_query = $conn->prepare("UPDATE *TABLE* SET introtext = ? WHERE id = ?");
if ($query->execute(array($introtext, $row->id)))
echo $row->id . " Done <br>";
else
echo $row->id . " Err<br>";
}
} catch(PDOexception $e) {
echo $e->getMessage();
}
$conn = null;
When I run the script, it outputs 41155 Done 4132 times. I'm not sure the logic here, but any help to get this working is appreciated.
I agree with Dagon that the database is not the place for that (what if tomorrow you decide that <span> should wrap another HTML tag?).
Anyway, it sounds like a one-time operation, so I wouldn't use PHP. Just run a MySQL client (the command line mysql, or Workbench, and use a query like this:
UPDATE *TABLE*
SET introtext = CONCAT('<span class="*SPAN CLASS*">', introtext, '</span>')
WHERE id >= 41155
One note about your current code: you're never executing the UPDATE query! You just prepare the statement, then instead of executing $update_query, you're executing $query again! That's why you're always printing the same id.