Checking Table exists before inserting php sql - php

I am trying to check if a table exists before entering the data into it. I am trying mysql_query and getting errors that I should be using mysqli, but it does not seem to be working for me.
This is my code so far:
$AllData = $_POST["table"];
foreach ($AllData as $sigleData) {
$table = $sigleData['name'];
$columns = implode(", ", $sigleData['columns']);
$columnData = implode(" ',' ", $sigleData['data']);
// Insert into database tuple data
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";
if ($dbConnectionT->query($sqlQuery) == TRUE) {
echo "database updated";
echo "</br>";
}
}

Try this way to check table exists or not using this custom function and then insert row to your db.
function check_table_exist($table){
global $dbConnection; // see here global connection variable
$sql = "SHOW tables LIKE '".$table."'";
$res = $dbConnection->query($sql);
return ($res->num_rows > 0);
}
#check first table exists or not
if(check_table_exists($table)){
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";
//do other stuff........
}else{
echo "Table Not Exists";
die('Going Out');
}

Table name is accepted as POST parameter, seriously !! - bad practice.
You can do various check to table existence like
DESC tbl_name;
SHOW CREATE TABLE tbl_name;
SHOW TABLES like 'tbl_name';

Related

Using variables in MySQL UPDATE - (PHP/MySQL)

I am trying to use variables in mysql update code, but i got the else {echo error message}.
$overwriteName = "UPDATE name SET name = '{$steamprofile['personaname']}' WHERE steamid = '{$steamprofile['steamid']}';";
if ($db->query($overwriteName) === TRUE) {
echo "success";
} else {
echo "error";
}
An easy way of doing this is using prepared statement:
(it's also more secure than using query, see the link for more information)
if($stmt = $db->prepare('UPDATE name SET name = ? WHERE steamid = ?')){ // prepare the query
$stmt->bind_param('ss',$steamprofile['personaname'],$steamprofile['steamid']); // bind your parameters (as many s as there are variables)
$stmt->execute();
// then your code
}
PHP doesn't substitute the value of a variable if you enclose it between simple quotes '$variable'.
In the query declaration, enclose $steamprofile['personaname'] and $steamprofile['steamid'] like this:
$overwriteName = "UPDATE name SET name = " . "$steamprofile['personaname']" . " WHERE steamid = " . "$steamprofile['steamid']" . ";";
Or don't enclose them at all:
$overwriteName = "UPDATE name SET name = " . $steamprofile['personaname'] . " WHERE steamid = " . $steamprofile['steamid'] . ";";

How to enable a log just before the php query

I am trying the approach of 'adding a log just before the php query'; in effort to achieve the ability to print a 'time stamp' when my mySQL database has been updated.
my queries look like this.
require_once('include/connect.php');
$q = $_GET['q'];
//echo $q;
//$plan=substr($q,0,4);
//$spec=substr($q,4);
list($plan, $ptype, $spec) = explode('_', $q);
//echo $plan . ", " . $spec;
//$query="SELECT vphp.tbl_provider_types.`TYPE` from coolDB.tbl_provider_types where vphp.tbl_provider_types.".$q." = 'Y';";
$query= "SELECT tbl_sourcespecheader.specID, coolDB.tbl_sourcespecheader.Specialty_Header from vphp.tbl_provider_types left join coolDB.tbl_sourcespecheader on coolDB.tbl_provider_types.ID = coolDB.tbl_sourcespecheader.TypeID where coolDB.tbl_provider_types.ID = " . $spec . " and coolDB.tbl_sourcespecheader." . $plan . " = 'Y';";
$result = mysqli_query($connection, $query);
//Populate result in HTML which will be returned via AJAX
echo "<h4>Please select from these " . $ptype . " specialties:</h4>";
echo "<select id='type' multiple='' name='specialty'><option selected="selected" value="nospec"></option>";
while($row = mysqli_fetch_array($result))
{
echo "<option value='" . $row['specID'] . "'><a href='#' id='" . $row['specID'] . "' onclick='getSelected(this.id);return false' style='text-decoration: none'>" . $row['Specialty_Header'] . "</a></option>";
}
echo "</select>";
//Close database connection
mysqli_close($connection);
Better use triggers. You need to create log table to be able to insert all data you needed. Below is the example.
DELIMITER $$
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employees_audit
SET action = 'update',
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
changedat = NOW();
END$$
DELIMITER ;
If you are using phpMyadmin. Go to that and find the trigger menu. There you can create triggers.

Cannot update the row in mysql via php

I tried to update a row in table showtable
Bugupdate
By using the php code below, binding a bugID to a SQL UPDATE statement to update the row I want to but it doesn't seem to work, is it the problem lie in my SQL statement ?
$id = $_GET['update'];
$games = htmlentities($_POST['games']);
$version = htmlentities($_POST['version']);
$platform = htmlentities($_POST['platform']);
$frequency = htmlentities($_POST['frequency']);
$proposal = htmlentities($_POST['proposal']);
$SQLstring2 = "UPDATE " .$TableName. " SET Game=?,Version=?,Platform=?,Frequency=?,Proposed solution=? WHERE BugID= " .$id;
if ($stmt = mysqli_prepare($DBconnect, $SQLstring2)) {
mysqli_stmt_bind_param($stmt,'sssss', $games, $version, $platform, $frequency, $proposal);
$QueryResult2 = mysqli_stmt_execute($stmt);
if ($QueryResult2 === FALSE) {
echo "<p>Unable to execute the query.</p>"
. "<p>Error code "
. mysqli_errno($DBconnect)
. ": "
. mysqli_error($DBconnect)
. "</p>";
} else {
echo "<h1> Thank you for your contribution";
}
mysqli_stmt_close($stmt);
}
mysqli_close($DBconnect);
Try to rename Proposed solution column to Proposed_solution and adapte the sql query like this :
$SQLstring2 = "UPDATE " .$TableName. " SET Game=?,Version=?, Platform=?, Frequency=?, Proposed_solution=? WHERE BugID= " .$id;

Create and insert variables into mysql from for loop using php

I want to create an array or variables that can be inserted into the sql query instead of do it manually like in my code below.
Is this possible with the simple php, not using PDO, just some kind of trick that will solve this issue.
You can see that I manually inserted 10 columns and 10 values, can I do it shorter?
So, I want to have a variable/array that will consist pt1-pt10 and another that will be consisted of a[1]-a[10].
for($j=1;$j<11;$j++) {
$a[$j] = "";
}
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'my_db';
$table = 'jos_answers';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("INSERT into ".$table."(id, title, pt1, pt2, pt3, pt4, pt5, pt6, pt7, pt8, pt9, pt10) VALUES ((select id from jos_content where title='$title'),'$title','$a[1]','$a[2]','$a[3]','$a[4]','$a[5]','$a[6]','$a[7]','$a[8]','$a[9]','$a[10]')");
?>
for($j=1;$j<11;$j++) {
$a["pt".$j] = $j;
}
"INSERT into ".$table. "(id, title,".implode(",", array_keys(a)).") VALUES ((select id from jos_content where title='$title'),'$title',".implode(",", array_values(a)).")";
Try this:
$insert = "INSERT INTO" . $table . "(id, title,";
$value = " VALUES((select id from jos_content where title='$title'),'$title',";
for($x = 1; $x < 11; $x++){
$insert .= " pt" . $x . ",";
$value .= " '$a[" . $x . "]'," //this line is iffy....
}
$insert = substr($insert, 0, -1);//to remove last comma
$value = substr($value, 0, -1);//to remove last comma
$insert .= ")";//final paren
$value .= ")";//final paren
$sql = $insert . $value; //combine parts
$result = mysql_query($sql);
The reason I think that line is iffy is becuase the ' ' surronding the varibles kinda confuses me. Do you want the varibles value to be inserted to the DB? If so I would go with this line instead:
$values .= " " . $a[$x] . ",";
If you want the ' and the values go with this:
$values .= " '" . $a[$x] . "',";
Here is a working example of the code edited a bit obviously because it is not in your SQL environment and you did not give us all the variable values: http://viper-7.com/cDAcRl
Good Luck!

Create table on master with data from slave in MySQL 5.1 and PHP 5.4

In MySQL 5.1 and PHP 5.4 I need to create temporary tables from the result of a query on a slave database. The problem is that I need the temporary table to be created on the Master (with data from the slave). It's the selection of the data for this table that carries all the overhead so I need the SELECT to happen on one of the slaves. The temporary table will be selected from for up to 2 hours, and I can't copy it to ALL the slaves (at least I don't think I can).
Here is what the code looks like:
$database->executeQuery ( "CREATE TABLE IF NOT EXISTS `" . $tableName . "` ENGINE = $engine CHARACTER SET utf8 ( " . $sql . ") " );
Again, the query in the $sql variable has to happen on the slave, while the table is created on the master.
Ok, turns out the way for me was to grab the result set in PHP from the slave, then create a SQL statement to insert it into the master.
public function createTemporaryTable ($tableName, $keyField = '', $sql = '', $engine = 'MEMORY') {
global $apdatabase;
$dbObj = new apdatabase();
$dbObj->setSqlCache(false);
$dbObj->setSqlBigResult(true);
$dbObj->setSqlCalcFoundRows(false);
$dbObj->setResultMode(MYSQLI_USE_RESULT);
$sql = $sql ? $sql : $this->getQuery();
$dbObj->executeQuery($sql);
$partsArr = array();
$foundRows = false;
$resultArr = $dbObj->getResultArray();
$dbObj->freeResultSet();
if (! count($resultArr)) {
return;
}
/*
* Set up the statement we will use to create the table definition
*/
$firstRow = $resultArr[0];
$fields = '';
$fieldDefinitionStr = '';
foreach ($firstRow as $field => $data) {
if ($fields != "") {
$fields .= ",";
$fieldDefinitionStr .= ",";
}
$fields .= $field;
$fieldDefinitionStr .= "`" . $field . "` VARCHAR (1024)";
}
parent::executeQuery("DROP TABLE IF EXISTS `" . $tableName . "`");
parent::executeQuery("CREATE TABLE `" . $tableName . "` ( " . $fieldDefinitionStr . ") ENGINE = $engine CHARACTER SET utf8");
/*
* Set up the sql to insert the remaining rows into our new table
*/
$sql = "INSERT IGNORE INTO `$tableName` ($fields) ";
$partsArr = array();
foreach ($resultArr as $row) {
$foundRows = true;
$rowSql = "(";
foreach ($row as $field) {
if ($rowSql != "(") {
$rowSql .= ",";
}
$rowSql .= "'" . $field . "'";
}
$rowSql .= ") ";
$partsArr[] = $rowSql;
}
parent::executeQuery($sql . "VALUES " . implode(', ', $partsArr));
if ($keyField) {
parent::executeQuery(" ALTER TABLE `" . $tableName . "` ADD KEY (`" . $keyField . "`) ");
}
}

Categories