Prepared statements in mysqli not working - mysql

Can someone explain to me why this isn't working. Trying to convert to prepared statements as per the advice of everybody but get stuck right at the beginning...the connection is fine and it returns no message, but there is no entry into my table (called nametable)
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "fidelio";
$dbname = "test";
$con = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")");
}
$query = "INSERT INTO nametable (fname, lname) values (?,?)";
$stmt = mysqli_prepare($con, $query);
$firstName = "simon";
$lastName = "morris";
mysqli_stmt_bind_param($stmt,"ss",$firstname, $lastname);
mysqli_stmt_execute($stmt);
printf("Error: %s.\n", $stmt->error);
$stmt->close();
?>
I added the last 2 lines and the error that comes back is
Error: .
This works just fine but the prepared statements do not....anyone know why?
$sql="INSERT INTO nametable (fname, lname)
VALUES ('$firstName', '$lastName')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}

try this
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "fidelio";
$dbname = "test";
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$firstName = "simon";
$lastName = "morris";
if ($stmtb = $mysqli->prepare("INSERT INTO nametable (fname, lname) values (?,?)")) {
$stmtb->bind_param('ss',$firstName, $lastName);
$stmtb->execute();
}else {printf("Prepared Statement Error: %s\n", $mysqli->error);}

Related

Split the database by date

I have large MySQL database on production (14 GB). Sometimes I have to download it and work on it locally. This is of course problem. The database have 10 tables with field "date" and 5 tables without field "date".
Is there any easy way to download it for the last month? 10 tables with condition "data > '2020-07-24'" and full 5 other tables. I would like to dump it into one .sql file and next import it locally.
Unfortunately the database has some relations between 10 tables...
Try this code and its must be to create columns CREATED_DATE with any tables
i hope it will work :)
if you need AutoBackup with GoogleDrive
https://github.com/engacs/Autobackup-databse-to-GoogleDrive/
<?php
// ini_set('memory_limit', '1024M');
// User home directory (absolute)
$homedir = "backup/"; // If this doesn't work, you can provide the full path yourself
// Site directory (relative)
$sitedir = "";
// Base filename for backup file
$fprefix = "sitebackup-";
// Base filename for database file
$dprefix = "dbbackup-";
// MySQL username
$dbuser = "root";
// MySQL password
$dbpass = "";
// MySQL database
$dbname = "";
// MySQL Host
$host = "localhost";
// Get connection object and set the charset
$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);
$conn->set_charset("utf8");
// Get All Table Names From the Database
$tables = array();
$sql = "SHOW TABLES";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
$sqlScript = "";
foreach ($tables as $table) {
// Prepare SQLscript for creating table structure
$query = "SHOW CREATE TABLE $table";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_row($result);
$sqlScript .= "\n\n" . $row[1] . ";\n\n";
$form_date='2020-08-01'; // Split From Date
$to_date='2020-08-31'; // Split to Date
$query = "SELECT * FROM $table "; //
// if you whant to use Split the database by date
// $query .=" WHERE CREATED_DATE >= DATE(CONCAT_WS('-', '2020', '08', '01')) AND CREATED_DATE < DATE(CONCAT_WS('-', '2020', '08', '31'))"
// $query .=" WHERE CREATED_DATE >= '$form_date' AND CREATED_DATE < '$to_date' ";
$result = mysqli_query($conn, $query);
$columnCount = mysqli_num_fields($result);
// Prepare SQLscript for dumping data for each table
for ($i = 0; $i < $columnCount; $i ++) {
while ($row = mysqli_fetch_row($result)) {
$sqlScript .= "INSERT INTO $table VALUES(";
for ($j = 0; $j < $columnCount; $j ++) {
$row[$j] = $row[$j];
if (isset($row[$j])) {
$sqlScript .= '"' . $row[$j] . '"';
} else {
$sqlScript .= '""';
}
if ($j < ($columnCount - 1)) {
$sqlScript .= ',';
}
}
$sqlScript .= ");\n";
}
}
$sqlScript .= "\n";
}
if(!empty($sqlScript))
{
// Save the SQL script to a backup file
$backup_file_name = $homedir.$dprefix.$dbname . '_' . $uid . '.sql';
$fileHandler = fopen($backup_file_name, 'w+');
$number_of_lines = fwrite($fileHandler, $sqlScript);
fclose($fileHandler);
}
Yes, look at mysqldump's --where option.

Syntax error, unexpected '$query' (T_VARIABLE)

$koneksi = mysqli_connect($host_name, $username, $password, $database);
$query = mysqli_query($koneksi, "SELECT * FROM pembeli");
$hasil = mysqli_query($query);
while ( $buyer = mysqli_fetch_assoc($hasil)){
echo $buyer ['Nama'];
echo $buyer ['Barang'];
echo $buyer ['Retribusi'];
}
I have that line of code, its produce syntax error unexpected '$query'(T_VARIABLE). Whats wrong ?
In mysqli no need to write :- mysql_select_db($database);
because fourth param in is database name
example :- mysqli_connect($localhost, $username, $password, $database);
Update your code as shown below
$database = "jaka_crud_ci";
$koneksi = mysqli_connect($host_name, $username, $password, $database);
$query = mysqli_query($koneksi, "SELECT * FROM pembeli");
while ( $buyer = mysqli_fetch_assoc($query)){
echo $buyer['Nama'];
echo $buyer['Barang'];
echo $buyer['Retribusi'];
}

How to Join/Combine two table when export Mysql data to Excel Download?

I Maintain 4 tables.
Table 1(table name: products)-> pro_id, pro_model, price
Table 2(table name: pro_description)-> id, pro_id, pro_name, pro_desp
Table 3(table name: pro_to_category)-> id, pro_id, cat_id
Table 4(table name: category)-> cat_id, cat_desp
Now I wants to download the fields, when I export mysql data to excel
download, pro_id, pro_name, pro_desp, price, pro_model, category
(notes: category needs the cat_desp, no need cat_id)
Thanks for advance. help me to solve. :(
<?php
/*******EDIT LINES 3-8*******/
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "username"; //MySQL Username
$DB_Password = "password"; //MySQL Password
$DB_DBName = "databasename"; //MySQL Database Name
$DB_TBLName = "tablename"; //MySQL Table Name
$filename = "excelfilename"; //File Name
/*******YOU DO NOT NEED TO EDIT ANYTHING BELOW THIS LINE*******/
//create MySQL connection
$sql = "Select * from $DB_TBLName";
$Connect = #mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = #mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
//execute query
$result = #mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
$file_ending = "xls";
//header info for browser
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
/*******Start of Formatting for Excel*******/
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");
//end of printing column names
//start while loop to get data
while($row = mysql_fetch_row($result))
{
$schema_insert = "";
for($j=0; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
?>
Try a query along these lines:
SELECT
t1.pro_id,
t2.pro_name,
t2.pro_desp,
t1.price,
t1.pro_model,
t4.cat_desp
FROM products t1
INNER JOIN pro_description t2
ON t1.pro_id = t2.pro_id
INNER JOIN pro_to_category t3
ON t1.pro_id = t3.pro_id
INNER JOIN category t4
ON t3.cat_id = t4.cat_id

how to add multiple JSON data links to Mysql

I have a lot of links which has JSON data inside and i need the data from links to mysql, what could be fastest way for that ?
Is it possible to modify this code below to make it able to read from multiple urls ?
<?php
//connect to mysql db
$con = mysql_connect("username","password","") or die('Could not connect: ' . mysql_error());
//connect to the employee database
mysql_select_db("employee", $con);
//read the json file contents
$jsondata = file_get_contents('empdetails.json');
//convert json object to php associative array
$data = json_decode($jsondata, true);
//get the employee details
$id = $data['empid'];
$name = $data['personal']['name'];
$gender = $data['personal']['gender'];
$age = $data['personal']['age'];
$streetaddress = $data['personal']['address']['streetaddress'];
$city = $data['personal']['address']['city'];
$state = $data['personal']['address']['state'];
$postalcode = $data['personal']['address']['postalcode'];
$designation = $data['profile']['designation'];
$department = $data['profile']['department'];
//insert into mysql table
$sql = "INSERT INTO tbl_emp(empid, empname, gender, age, streetaddress, city, state, postalcode, designation, department)
VALUES('$id', '$name', '$gender', '$age', '$streetaddress', '$city', '$state', '$postalcode', '$designation', '$department')";
if(!mysql_query($sql,$con))
{
die('Error : ' . mysql_error());
}
?>
Here is an example of reading url's from a excel file.
I am using http://code.google.com/p/php-excel-reader/.
File - urls.xls.
It assumes this excel contains url's in the first column.
<?php
//connect to mysql db
$con = mysql_connect("username","password","") or die('Could not connect: ' . mysql_error());
//connect to the employee database
mysql_select_db("employee", $con);
$data = new Spreadsheet_Excel_Reader("urls.xls",false);
$rows = $data->rowcount(0);
for( $i=0;$i<$rows;$i++ ) {
//read the json file contents
$jsondata = file_get_contents($data->val($i,0));
//convert json object to php associative array
$data = json_decode($jsondata, true);
//get the employee details
$id = $data['empid'];
$name = $data['personal']['name'];
$gender = $data['personal']['gender'];
$age = $data['personal']['age'];
$streetaddress = $data['personal']['address']['streetaddress'];
$city = $data['personal']['address']['city'];
$state = $data['personal']['address']['state'];
$postalcode = $data['personal']['address']['postalcode'];
$designation = $data['profile']['designation'];
$department = $data['profile']['department'];
//insert into mysql table
$sql = "INSERT INTO tbl_emp(empid, empname, gender, age, streetaddress, city, state, postalcode, designation, department)
VALUES('$id', '$name', '$gender', '$age', '$streetaddress', '$city', '$state', '$postalcode', '$designation', '$department')";
if(!mysql_query($sql,$con))
{
die('Error : ' . mysql_error());
}
}
?>
Hope this helps.

How would I add to table values then show the total on my website

I want to add two table totals together, and then place it on my website here's the code I tried.
<?php
$host = "localhost";
$username = "runerebe_online";
$password = "***";
$db_name = "runerebe_online";
mysql_connect("$host", "$username", "$password") or die (mysql_error ());
mysql_select_db("$db_name") or die(mysql_error());
$host = "localhost";
$username = "runerebe_online2";
$password = "***";
$db_name = "runerebe_online2";
mysql_connect("$host", "$username", "$password") or die (mysql_error ());
mysql_select_db("$db_name") or die(mysql_error());
$total = "SELECT (online + online2)";
$rs = mysql_query($total);
while($row = mysql_fetch_array($rs)) {
echo $row['total'];
}
mysql_close();
?>
This is the error printing when I use this
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/runerebe/public_html/home/index.php on line 63
This is line 63, and what it contains
63: while($row = mysql_fetch_array($rs)) {
64: echo $row['total'];
65: }
Your query is invalid. That is why mysql_query() fails and returns FALSE instead of a resource that is needed for mysql_fetch_array() to succeed.
If you need to read two values from two different databases and if a user has permissions granted to do select on both databases and is currently connected to the database online you can do that with a statement like this
SELECT
(SELECT SUM(o2.columnname) FROM runerebe_online2.tablename o2) +
(SELECT SUM(columnname) FROM tablename) TOTAL
Otherwise you need to retrieve two values separately in php like this
//Connect and get a value from db 'runerebe_online'
...
$db_name = "runerebe_online";
$link1 = mysql_connect("$host", "$username", "$password") or die (mysql_error ());
mysql_select_db($db_name, $link1) or die(mysql_error());
$sql = "SELECT SUM(columnname) subtotal FROM tablename"
$result = mysql_query($total, $link1);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$subtotal1 = $row['subtotal'];
mysql_free_result($result);
mysql_close($link1);
//Connect and get a value from db 'runerebe_online2'
...
$db_name = "runerebe_online2";
$link2 = mysql_connect("$host", "$username", "$password") or die (mysql_error ());
mysql_select_db("$db_name", $link2) or die(mysql_error());
$sql = "SELECT SUM(columnname) subtotal FROM tablename"
$result = mysql_query($total, $link2);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$subtotal2 = $row['subtotal']
mysql_free_result($result);
mysql_close($link1);
$total = $subtotal1 + $subtotal2;
echo $total;
...