How to insert data from a select query using php - php

I wan to insert data to mysql table from another database which is connected via ODBC.But I cannot enter into the while loop, here is my code -
N.B: For security I dont provide db name, user and pass.
ODBC connection declared as 'connStr'
<?php
$connStr = odbc_connect("database","user","pass");
$conn = mysqli_connect("server","user","pass","database");
//$result_set=mysqli_query($conn,$datequery);
//$row=mysqli_fetch_array($result_set);
echo "<br>";
echo "<br>";
$query="select cardnumber, peoplename, creditlimit, ROUND(cbalance,2) as cbalance, minpay from IVR_CardMember_Info
where cardnumber not like '5127%'" ;
$rs=odbc_exec($connStr,$query);
$i = 1;
while(odbc_fetch_row($rs))
{ //echo "Test while";
$cardnumber=odbc_result($rs, "cardnumber");
$peoplename=odbc_result($rs, "peoplename");
$creditlimit=odbc_result($rs, "creditlimit");
$cbalance=odbc_result($rs, "cbalance");
$minpay=odbc_result($rs, "minpay");
$conn = mysqli_connect("server","user","pass","database");
$sql= "INSERT INTO test_data(cardnumber, peoplename, creditlimit, cbalance, minpay) VALUES ('cardnumber', 'peoplename', 'creditlimit', 'cbalance', 'minpay') ";
if(!(mysqli_query($conn,$sql))){
//echo "Data Not Found";
echo "<br>";
}
else{
echo "Data Inserted";
echo "<br>";
}
echo $i++ ;
}
echo "<br>";
odbc_close($connStr);
?>
How can I solve this?

If you really want to understand why you can't enter while() {...}, you need to consider the following.
First, your call to odbc_connect(), which expects database source name, username and password for first, second and third parameter. It should be something like this (DSN-less connection):
<?php
...
$connStr = odbc_connect("Driver={MySQL ODBC 8.0 Driver};Server=server;Database=database;", "user", "pass");
if (!$connStr) {
echo 'Connection error';
exit;
}
...
?>
Second, check for errors after odbc_exec():
<?php
...
$rs = odbc_exec($connStr, $query);
if (!$rs) {
echo 'Exec error';
exit;
}
...
?>

you can do it with just SQL check it here, like:
INSERT INTO test_data(cardnumber, peoplename, creditlimit, cbalance, minpay)
SELECT cardnumber, peoplename, creditlimit,
ROUND(cbalance,2) as cbalance, minpay from IVR_CardMember_Info
where cardnumber not like '5127%'

Related

Delete a users data from SQL using PHP

Hi im trying to delete a users booking detials when the user clicks delete in my bookingbeforedeltion.php file but for some reason when I test my php file once I click delete it goes to my delete.php screen and says it failed to delete from database and has the error Undefined index: rn. Is my rn not defined? Sorry Im new to this. Here is my code below:
bookingbeforedeltion.php:
<!DOCTYPE HTML>
<html><head><title>BookingBeforeDeletion</title> </head>
<body>
<?php
include "config.php";
$DBC = mysqli_connect("127.0.0.1", DBUSER , DBPASSWORD, DBDATABASE);
if (!$DBC) {
echo "Error: Unable to connect to MySQL.\n".
mysqli_connect_errno()."=".mysqli_connect_error() ;
exit;
};
echo "<pre>";
$query = 'SELECT roomname, checkindate, checkoutdate FROM booking';
$result = mysqli_query($DBC,$query);
if (mysqli_num_rows($result) > 0) {
echo "Delete Bookings" ?><p><?php
while ($row = mysqli_fetch_assoc($result)) {
echo "Room name: ".$row['roomname'] . PHP_EOL;
echo "Check in date: ".$row['checkindate'] . PHP_EOL;
echo "Check out date: ".$row['checkoutdate'] . PHP_EOL;
?>
[Cancel]
<?php
echo "<hr />";
}
mysqli_free_result($result);
}
echo "</pre>";
echo "Connectted via ".mysqli_get_host_info($DBC);
mysqli_close($DBC);
?>
</body>
</html>
delete.php:
<!DOCTYPE HTML>
<html><head><title>BookingBeforeDeletion</title> </head>
body>
<?php
include "config.php";
$DBC = mysqli_connect("127.0.0.1", DBUSER , DBPASSWORD, DBDATABASE);
if (!$DBC) {
echo "Error: Unable to connect to MySQL.\n".
mysqli_connect_errno()."=".mysqli_connect_error() ;
exit;
};
echo "<pre>";
$roomname=$_GET['rn'];
$query = "DELETE bookingID, roomname, checkindate, checkoutdate, contactnumber,
bookingextras, roomreview, customerID, roomID FROM booking WHERE roomname =
'$roomname'";
$result = mysqli_query($DBC,$query);
if($result)
{
echo "<font color='green'> Booking deleted from database";
}
else {
echo "<font color='red'> Failed to delete booking from database";
}
?>
and I think this will help:
As mentioned above, you need to print it from the PHP
<a href= 'delete.php?rn=$result[roomname]'>
// To
<a href= 'delete.php?rn=<?= $row['roomname'] ?>'>
// Explanation:
// 1. <?= ... ?> is the short form of <?php echo ... ?>
// 2. The `roomname` came from $row, not $result ($result is the MySQLi Object)
// 3. You need to quote the `roomname` because without it `roomname` will be readed
// as Constant, and may Throw a Warning message
//
Your DELETE is incorrect, the correct one is DELETE FROM ... WHERE ...
$query = "DELETE bookingID, roomname, checkindate, checkoutdate, contactnumber,
bookingextras, roomreview, customerID, roomID FROM booking WHERE roomname =
'$roomname'";
// To
$query = "DELETE FROM booking WHERE roomname = '$roomname'";
EXTRA:
3. You can assign a default value to $roomname
$roomname=$_GET['rn'];
// To
$roomname=$_GET['rn'] ?? 'default if null';
// if the rn index doesnt exist, the $roomname value will be `default if null` instead of throwing a Warning
Try to use Prepared-Statement SQL instead of writing it. (I dont know the example, but it can prevent SQL Injection)

Displaying fields in php from MS Access database

I have a simple studentinfo.accdb. I was able to connect to this database using php. Moreover, the values of the 'ID' column(primary key) are also being displayed. however, the field values are not. The error message is:
Connected
ID : 1
Warning: odbc_result(): Field class not found in
C:\xampp\htdocs\connect\index.php on line 20
The following is my code:-
<?php
$con=odbc_connect("studentinfo", "", "");
if($con)
{
echo "Connected<br>";
}
else
{
echo "Failed";
}
$sql="select * from Table1 WHERE ID = 1";
$result=odbc_exec($con, $sql);
while ($row=odbc_fetch_array($result)) {
echo "ID : ". $row['ID'];
if(isset($_GET['tName'])){
echo "NAME : ". $row['tName'];}
$asd = odbc_result($result, "class");
echo $asd;
// echo "CLASS :".$row['class'];
echo "<br/>";
}
?>
I have used an isset() and clearly the fileds are not set for some reason. Please help!

Checking whether username exists in MySQLi Database and PHP

I have been working on a website which has a xampp server and a database called users with a table called AccountDetails. About a year ago I got it to work perfectly, but the server I was using then required MySQL not MySQLi. Now I have to use MySQLi and can't even get the simplest of sql's SELECT function to work, any ideas would be much appreciated.
<?php
$link = mysqli_connect("localhost:3306", "root","", "users");
if(mysqli_connect_errno($link)){
echo "MySql Error: " . mysqli_connect_error();
} else {
echo"Connection Successful <br></br>";
}
echo("Check if still working <br></br>");
// -----------------------------//
echo("Its running <br></br>");
$result = $link->query("SELECT ID, UserName FROM AccountDetails");
return $result->result();
var_dump($result);
mysqli_close($link);
?>
The Query itself works when I plug it into the phpmyadmin SQL section and it returns the values that I expect it too.
I've spent days looking online for different answers but none of them work, and the var_dump only gives me "bool(false)" which I don't think I should be getting.
You can try this code
<?php
$link = mysqli_connect("localhost:3306", "root","", "users");
if(mysqli_connect_errno($link)){
echo "MySql Error: " . mysqli_connect_error();
} else {
echo"Connection Successful <br></br>";
}
echo("Check if still working <br></br>");
// -----------------------------//
echo("Its running <br></br>");
$sql_select = "SELECT * FROM AccountDetails";
$result = $link->query($sql_select);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "UserName: " . $row['UserName']. "<br>";
}
} else {
echo "No Records";
}
$link->close();
?>

How can I check for duplicate usernames using PHP and MySQL?

I'm just learning PHP and I thought it would be a good idea to learn some MySQL too.So I started working on the code and for some strange reason I keep getting duplicate users which is really really bad.
<?php
$link = mysqli_connect(here i put the data);
if(!$link)
{
echo "Error: " . mysqli_connect_errno() . PHP_EOL;
exit;
}
else
{
if(isset($_POST['user']))
{ echo "User set! "; }
else { echo "User not set!"; exit; }
if(isset($_POST['pass']) && !empty($_POST['pass']))
{ echo "Password set! "; }
else { echo "Password not set!"; exit; }
$num = mysqli_num_rows(mysqli_query("SELECT * FROM `users` WHERE ( username = "."'".$_POST['user']."' )"));
if($num > 0)
{ echo "Cannot add duplicate user!"; }
mysqli_close($link);
}
?>
For some strange reason I don't get the output I should get.I've tried some solutions found here on StackOverflow but they didn't work.
The first parameter of connectionObject is not given in mysqli_query:
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( `username` = '".$_POST['user']."' )"));
//----------------------------------^^^^^^^
Also, your code is vulnerable to SQL Injection. A simple fix would be:
$_POST['user'] = mysqli_real_escape_string($link, $_POST['user']);
mysqli_query must receive two parameters in order to work. In this case, your mysqli_connect.
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( username = "."'".$_POST['user']."' )"));
Also, you can be affected by SQL Injection, in this code.
Never add user input directly in your queries without filtering them.
Do that to make your query more readable and safe:
$u_name=mysqli_real_escape_string($link, $_POST['user']);
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( username = '$u_name' )"));
To use mysqli_* extension, you must include your connection inside of the parameters of all queries.
$query = mysqli_query($link, ...); // notice using the "link" variable before calling the query
$num = mysqli_num_rows($query);
Alternatively, what you could do is create a query() function within your website, like so:
$link = mysqli_connect(...);
function query($sql){
return mysqli_query($link, $sql);
}
and then call it like so:
query("SELECT * FROM...");
This could be a problem of race condition.
Imagine that two users wants to create the same username at the same time.
Two processes will execute your script. So both scripts select from database and find out that there is not an user with required username. Then, both insert the username.
Best solution is to create unique index on username column in the database.
ALTER TABLE users ADD unique index username_uix (username);
Then try insert the user and if it fails, you know the username exists ...
Here's how to write your code using prepared statements and error checking.
Also uses a SELECT COUNT(*)... to find the number of users instead of relying on mysqli_num_rows. That'll return less data from the database and just seems cleaner imo.
<?php
$link = mysqli_connect(here i put the data);
if(!$link) {
echo "Error: " . mysqli_connect_errno() . PHP_EOL;
exit;
}
else if(!isset($_POST['user'])) {
echo "User not set!"; exit;
}
echo "User set! ";
if(!isset($_POST['pass']) || empty($_POST['pass'])) {
echo "Password not set!"; exit;
}
echo "Password set! ";
$query = "SELECT COUNT(username)
FROM users
WHERE username = ?";
if (!($stmt = $mysqli->prepare($query))) {
echo "Prepare failed: (" . mysqli_errno($link) . ") " . mysqli_error($link);
mysqli_close($link);
exit;
}
$user = $_POST ['user'];
$pass = $_POST ['pass'];
if(!mysqli_stmt_bind_param($stmt, 's', $user)) {
echo "Execute failed: (" . mysqli_stmt_errno($stmt) . ") " . mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
exit;
}
if (!mysqli_execute($stmt)) {
echo "Execute failed: (" . mysqli_stmt_errno($stmt) . ") " . mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
exit;
}
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
$num = $row[0];
if($num > 0) {
echo "Cannot add duplicate user!";
}
}
mysqli_stmt_close($stmt);
mysqli_close($link);
please do suggest fixes to syntax, this was typed from a phone

mysqli->execute get error but no error is output

I have the next php code:
<?php
mysqli_report(MYSQLI_REPORT_ALL);
$mysqli = new mysqli("localhost","mybd","mypass");
if ($mysqli->connect_errno) { echo "Error connect<br/>"; }
else {
$mysqli->select_db("database1");
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]); // shows correct database selected
$result->close();
}
$sentencia = $mysqli->prepare("select pass from users Where name ='ronald'");
echo "Prepare error:".$mysqli->error."<br/>";
if (!$sentencia) echo "<br/>sentencia is null<br/>";
if ($sentencia->execute)
{
$sentencia->bind_result($cpass);
$sentencia->fetch();
echo "Passwd:".$cpass."<br/>";
$con="checkpass";
if (($con!=$cpass) && (md5($con)!=$cpass))
{
echo "OK<br/>";
}
else echo "NO OK<br/>";
}
else echo "<br/>Error execute: ".$mysqli->error;
}
mysqli_report(MYSQLI_REPORT_OFF);
?>
Problems are:
- $mysqli->error shows nothing. No error. Always empty string.
- $sentencia->execute always return null, and then always echo "Error execute:", but no information about error.
Database selected shows ok. It select the right database. This is an example. Really the name is passed with "$sentencia->bind_param("s",$user);" but with this, I get apache error of "no object".
I don't know why it happens. The SQL is checked and is Ok.
Thanks.
Shouldn't execute be a function nor property?
http://php.net/manual/en/mysqli-stmt.execute.php
if ($sentencia->execute())
{
}

Categories